讨论:FormsAuthentication.SetAuthCookie有BUG?
7707 2006-06-30 09:45:18 SEE: http://community.csdn.net/Expert/topic/4851/4851496.xml?temp=.6346094
最初认为代码有问题,把SDK中带的例子运行一遍,也是不行.
折腾了两天,终于搞定.我认为是2.0改了SetAuthCookie默认的50年,替换为web.config中的timeout值,也就是说SetAuthCookie("user",true)保存30分钟,关闭浏览器不丢失.false则关闭浏览器丢失. 但帮助文档中为何找不到只言片语?另外网上上狗一下,大把文章说SetAuthCookie默认50年...
但愿我的经历对各位有所帮助
继续郁闷,继续散分
如下代码正确运行:
protected void loginButton_Click(Object o, EventArgs e)
{
if (!Valid())
return;
User user = new User();
user.IP = Context.Request.UserHostAddress;
user.Username = username.Text.Trim();
user.Password = password.Text.Trim();
int valid = UserClass.Login(user);
if (valid > 0)
{
DateTime outtime = DateTime.Now.AddMinutes(20);
if (autoLogin.Checked)//自动登录
outtime = DateTime.Now.AddYears(100);//存 TMD 100年
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
valid.ToString(),//用户ID
DateTime.Now,//票证发出时间
DateTime.Now.AddYears(50), // 过期日间
false, // 跨浏览器保存
user.IP,//用户IP
FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);//加密
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authCookie.Secure = false;//非HTTPS
Context.Response.Cookies.Add(authCookie);
//FormsAuthentication.SetAuthCookie(valid.ToString(), autoLogin.Checked);
//FormsAuthentication.RedirectFromLoginPage(valid.ToString(), autoLogin.Checked);
if (ToaspContext.Current.ReturnUrl != String.Empty)
Context.Response.Redirect(ToaspContext.Current.ReturnUrl);
Context.Response.Redirect(Globals.ApplicationVRoot);
}
else if (valid == -1)
{
MessageBox.Show(username, Res.Get("Login_UsernameNotFound"));
}
else if (valid == -2)
{
MessageBox.Show(password, Res.Get("Login_PasswordFailure"));
}
}