日期:2014-05-17 浏览次数:20565 次
protected void btnLogin_Click(object sender, EventArgs e)
{
userName = txtUserName.Text.Trim();
pwd = txtPwd.Text.Trim();
if (userName == "xzl" && pwd == "123")
{
////方式一:授权并且自动跳转。
//FormsAuthentication.RedirectFromLoginPage(userName, false);//将经过身份验证的用户重定向回“最初请求的 URL 或默认 URL”。
////方式二:授权,自由控制跳转。
//FormsAuthentication.SetAuthCookie(userName, false);//发放凭证
//Response.Redirect("Default.aspx");
////方式三(1):自定义授权,自由控制转向。(方式三1中,效果和方式一、二中差不多)
//创建加密的 Forms 身份验证票证的 FormsAuthenticationTicket 对象。
//FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddHours(1), false, "userDate", FormsAuthentication.FormsCookiePath);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userName, false, 300);
//根据“加密的 Forms 身份验证票证的 FormsAuthenticationTicket 对象”生成一个字符串,该字符串存放客服端cookie中。
string encTicket = FormsAuthentication.Encrypt(ticket);
string cookieAuthKey = FormsAuthentication.FormsCookieName;//获取cookie中的key值,该值根据配置文件<forms loginUrl="Login.aspx" name=".ASPXFORMSAUTH"></forms>中的“name”属性确定。
HttpCookie cookie = new HttpCookie(cookieAuthKey, encTicket);
cookie.Expires = DateTime.Now.AddDays(3);//设置cookie过期时间
Response.Cookies.Add(cookie);//发放凭证
string redirectUrlOld = FormsAuthentication.GetRedirectUrl(userName, false);//返回导致重定向到登录页的“原始请求的重定向 URL”。
Response.Redirect(redirectUrlOld);//重定向到原始页面
//“登录页”根据配置文件<forms loginUrl="Login.aspx" name=".ASPXFORMSAUTH"></forms>中的loginUrl确定。
//string loginUrl = FormsAuthentication.LoginUrl;//获取“登录页”。
//FormsAuthentication.RedirectToLoginPage();//定向到“登录页”。
////方式三(2):
//HttpCookie coo = FormsAuthentication.GetAuthCookie(userName,false);
//Response.Cookies.Add(coo);
//Response.Redirect("Default.aspx");
return;
}
Response.Write("用户名或密码错误!");
}