这俩天在搞 Forms 验证。终于搞出来了。。。

.net Forms 验证_用户名

web.config 配置:

<authentication mode="Forms">
<forms name="test" loginUrl="Login.aspx" defaultUrl="Main.aspx" timeout="4"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>。。。
</system.web>
<location path="Register.aspx" allowOverride="true">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
Login.aspx.cs

protected void LoginButton_Click(object sender, EventArgs e)
{
string userName = this.UserLogin.UserName;
string Pwd = this.UserLogin.Password;
if (userName == "李朴" && Pwd == "123")
{
FormsAuthentication.RedirectFromLoginPage(userName, this.UserLogin.RememberMeSet);
HttpCookie cookie = FormsAuthentication.GetAuthCookie(userName, this.UserLogin.RememberMeSet);
FormsAuthenticationTicket FormAt = FormsAuthentication.Decrypt(cookie.Value); //创建自定义数据
String UserData = "id=88|name=李朴|time=" + System.DateTime.Now.Second.ToString();
FormsAuthenticationTicket NewFormAt = new FormsAuthenticationTicket(FormAt.Version, FormAt.Name, FormAt.IssueDate, FormAt.Expiration, FormAt.IsPersistent, UserData, FormAt.CookiePath);
String EncryptedValue = FormsAuthentication.Encrypt(NewFormAt);
cookie.Value = EncryptedValue;
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, this.UserLogin.RememberMeSet), false);
}
else
{
Info.Text = "用户名和密码错误,请重新输入。";
}

}

Main.aspx.cs


protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.Name != "")
{
this.hplLogin.Text = HttpContext.Current.User.Identity.Name;
this.hplLogin.NavigateUrl = "";
//获得票据里的值:
FormsIdentity id = (FormsIdentity)User.Identity;
FormsAuthenticationTicket Ticket = id.Ticket;
this.Label1.Text = Ticket.UserData;

}
}

Register.aspx.cs :
protected void RegBtn_Click(object sender, EventArgs e)
{
FormsAuthentication.RedirectFromLoginPage(this.UserNameTxt.Text, true);
Response.Redirect(FormsAuthentication.GetRedirectUrl(this.UserNameTxt.Text, true), false);
}


作者:沐雪

文章均系作者原创或翻译,如有错误不妥之处,欢迎各位批评指正。本文版权归作者所有,如需转载恳请注明。

​​​ 为之网-热爱软件编程 http://www.weizhi.cc/​