在我的一个程序里使用了Forms身份验证,在验证通过后,我手动设置Cookie的过期时间为1年后,但是经过实验,发现这个设置未起作用,第二天还是需要重新登录在登录前,我还特意进入Cookie保存的目录:c:\Documents and Settings\Administrator\Local Settings\Temporary Internet Files
查看那个Cookies文件,过期时间也确实是2011年,如图(这个图是我刚刚再次登录的,所以时间是今天):
贴出我的源代码:
string uName = Login1.UserName;
if (FormsAuthentication.Authenticate(uName, Login1.Password))
{
bool remember = Login1.RememberMeSet;
//FormsAuthentication.SetAuthCookie(uName, remember);
if (!remember)
FormsAuthentication.RedirectFromLoginPage(uName, false);
else
{
// 使用下面的语句,只能记住30分钟左右
//FormsAuthentication.RedirectFromLoginPage(uName, true); HttpCookie cookie = FormsAuthentication.GetAuthCookie(uName, true);
cookie.Expires = DateTime.Now.AddYears(1); // 记住我时,设置1年有效
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, true));
}
}
查看那个Cookies文件,过期时间也确实是2011年,如图(这个图是我刚刚再次登录的,所以时间是今天):
贴出我的源代码:
string uName = Login1.UserName;
if (FormsAuthentication.Authenticate(uName, Login1.Password))
{
bool remember = Login1.RememberMeSet;
//FormsAuthentication.SetAuthCookie(uName, remember);
if (!remember)
FormsAuthentication.RedirectFromLoginPage(uName, false);
else
{
// 使用下面的语句,只能记住30分钟左右
//FormsAuthentication.RedirectFromLoginPage(uName, true); HttpCookie cookie = FormsAuthentication.GetAuthCookie(uName, true);
cookie.Expires = DateTime.Now.AddYears(1); // 记住我时,设置1年有效
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, true));
}
}
<forms loginUrl="Admin/Login.aspx" timeout="xxx">
_Timeout = (int) settings.Forms.Timeout.TotalMinutes;private static HttpCookie GetAuthCookie(String userName, bool createPersistentCookie, String strCookiePath, bool hexEncodedTicket) {
....
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
2, // version
userName, // User-Name
DateTime.Now, // Issue-Date
DateTime.Now.AddMinutes(_Timeout), // Expiration
createPersistentCookie, // IsPersistent
String.Empty, // User-Data
strCookiePath // Cookie Path
); 所以看来,我的要求有2个解决方案:
1、设置Web.config里的Forms的TimeOut;
2、自己创建票据最后修正代码为:
DateTime now = DateTime.Now;
DateTime end = now.AddYears(1);// 设置1年后过期
//建立身份验证票对象
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, uName, now, end, true, string.Empty);
string HashTicket = FormsAuthentication.Encrypt(Ticket); //加密序列化验证票为字符串
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket) { Expires = end };//生成Cookie
Response.Cookies.Add(cookie);// FormsAuthentication.SetAuthCookie();
Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, true));