这俩天在搞 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);
}