我有验证码:
var authTicket = new FormsAuthenticationTicket(/*blahblah....*/);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
var name = HttpContext.User.Identity.Name; // line 4
通过输入调试语句,我发现第4行的name
为空。但是,下次我在此浏览器会话中拨打电话时,HttpContext.User.Identity.Name
已正确设置。
那么什么时候设置这个值?
答案 0 :(得分:20)
如果给定的Request包含身份验证cookie,则将设置HttpContext.User.Identity.Name。在您的情况下,cookie刚刚被添加到响应中以供浏览器选择。如果存在,浏览器将在以下请求中添加cookie。
答案 1 :(得分:2)
从您的代码中看起来您要么必须致电:
FormsAuthentication.Authenticate(name, password)
或者,如果使用会员资格,则:
Membership.ValidateUser(name, password)