一个用asp.net实现Forms验证的例子

本文介绍如何在ASP.NET应用程序中配置web.config文件来实现不同文件夹的访问权限控制,包括登录验证流程及代码实现。
  1. Set related sections in web.config:

<authentication mode="Forms" >

<forms loginUrl="Login.aspx"

protection="All"

timeout="30"

name=".ASPXAUTH"

path="/"

requireSSL="false"

slidingExpiration="true"

defaultUrl="default.aspx"

cookieless="UseDeviceProfile"

enableCrossAppRedirects="false" />

</authentication>

  1. Put different kinds of files into different folders. This is because: before being visited, some files need users to login in, while others needn't.
  2. Set related sections in web.config to realize the function which is described in the 2nd point.

<system.web>

    

<authorization>

<allow users="*" />

</authorization>

</system.web>

<location path="Admin">

<system.web>

<authorization>

<deny users="?" />

</authorization>

</system.web>

</location>

<location path="Admin/NeedNotLogin.aspx">

<system.web>

<authorization>

<allow users="*" />

</authorization>

</system.web>

</location>

  1. Write codes in clicking event of the login button:

protected void btnLogin_Click(object sender, EventArgs e)

{

if( ValidateUser( txtUserName.Text , txtPassword.Text ))

{

HttpCookie authenticationCookie=FormsAuthentication.GetAuthCookie(txtUserName.Text,true);

authenticationCookie.Expires=DateTime.Now.AddDays(3);//three days.

Response.Cookies.Add(authenticationCookie);

 

Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUserName.Text,true));

}

else

{

Response.Write("invalid user!");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值