Skip to main content
 首页 » 编程设计

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

2024年02月13日19tuyile006

我正在像下面这样设置表单例份验证 cookie

FormsAuthentication.SetAuthCookie("test", true);

当我检查它是否返回 null 时...

Context.User.Identity.Name 

知道为什么会这样吗?谢谢

请您参考如下方法:

您应该始终在设置表单例份验证 cookie 后重定向:

public ActionResult SomeAction() 
{ 
    FormsAuthentication.SetAuthCookie("test", true);     
    return RedirectToAction("FooBar"); 
} 

只有在您重定向到的后续操作中,您才会正确初始化 User.Identity.Name。原因很简单:User.Identity.Name 属性是从请求 cookie(也称为传入 cookie)初始化的,而 FormsAuthentication.SetAuthCookie 正在设置表单例份验证到响应(也就是发出 cookie),以便在后续请求中将在请求中发送此 cookie。