简体   繁体   English

Context.User.Identity.Name在MVC 4中返回null

[英]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.

相关问题 使用 .mapuniquejsonkey 时@context.user.identity.name 为空 - @context.user.identity.name is null when using .mapuniquejsonkey MVC3 @ C​​ontext.User.Identity.Name为空值 - MVC3 @Context.User.Identity.Name empty value Context.User.Identity.Name null 即使在用户身份验证之后 - Context.User.Identity.Name null even after user authentication in identity 为什么在Windows Form Hub上下文中Context.User.Identity.Name为null? - Why Context.User.Identity.Name is null in Windows Form Hub Context? 在asp.net mvc中,context.User.Identity.Name的用途是什么? - In asp.net mvc what is the use of context.User.Identity.Name? 事件获取SqlDependency的火后获取Context.User.Identity.Name为空 - Getting Context.User.Identity.Name Null After Event Got Fire of SqlDependency 为什么Context.User.Identity.Name始终为空? - Why is Context.User.Identity.Name always empty? 为什么SignalR Context.User.Identity.Name为空? - Why is SignalR Context.User.Identity.Name empty? .NET 4.0-> 4.5 Context.User.Identity.Name在窗体身份验证后不再设置(总是返回Windows用户名) - .NET 4.0 -> 4.5 Context.User.Identity.Name is no longer set after Forms Authenication (always returns Windows username) User.Identity.Name 在 ASP.NET Core MVC 应用程序中返回 null - User.Identity.Name returns null in ASP.NET Core MVC application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM