什么时候HttpContext.User.Identity设置?

Sha*_*ica 24 .net asp.net asp.net-mvc

我有验证码:

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
Run Code Online (Sandbox Code Playgroud)

通过输入调试语句,我发现name第4行是空的.但是下次我在这个浏览器会话上打电话时,HttpContext.User.Identity.Name会正确设置.

那么这个值何时得到设定?

小智 21

如果给定的请求包含身份验证cookie,则将设置HttpContext.User.Identity.Name.在您的情况下,cookie刚刚被添加到响应中以供浏览器选择.如果存在,浏览器将在以下请求中添加cookie.