[英]Context.User.Identity.Name returns null in MVC 4
I'm setting the forms authentication cookie like this below 我正在设置下面的表单身份验证cookie
FormsAuthentication.SetAuthCookie("test", true);
and when i check if its set it returns null... 当我检查它的设置是否返回null ...
Context.User.Identity.Name
any ideas why this is happening? 任何想法为什么会这样? thanks
谢谢
You should always redirect after setting a forms authentication cookie: 设置表单身份验证cookie后,应始终重定向:
public ActionResult SomeAction()
{
FormsAuthentication.SetAuthCookie("test", true);
return RedirectToAction("FooBar");
}
It's only in the subsequent action you are redirecting to that you will get the User.Identity.Name
being properly initialized. 只有在您重定向到的后续操作中,才会正确初始化
User.Identity.Name
。 The reason for that is pretty simple: the User.Identity.Name
property is initialized from the Request cookies (aka incoming cookies) whereas the FormsAuthentication.SetAuthCookie
is setting the forms authentication to the response (aka emitting a cookie) so that on subsequent requests this cookie will be sent in the request. 原因很简单:
User.Identity.Name
属性是从Request cookie(也就是传入的cookie)初始化的,而FormsAuthentication.SetAuthCookie
是将表单身份验证设置为响应(也就是发出cookie),以便在后续请求中此cookie将在请求中发送。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.