用户在控制器中为空,但在View中有值

Uth*_*imi 4 authentication asp.net-mvc identity

我使用ASP.NET MVC 5Identityfor Authentication,我的问题是使用下面的代码:

User.Identity.IsAuthenticated
Run Code Online (Sandbox Code Playgroud)

User 是Null,但我在View Like下面使用了Above代码,它的工作正常,用户有价值.

  @if (User.Identity.IsAuthenticated)
            {...}
Run Code Online (Sandbox Code Playgroud)

什么事?

要做到这一点,我在谷歌上搜索并找到一种方法

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);
    }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 8

我怀疑你试图在控制器的构造函数中调用此方法.在HTTP请求执行管道中过早地调用此构造函数,并且HttpContext在那里不可用.您可以在Initialize方法中访问HttpContext:

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);

    // Now you can access the HttpContext and User
    if (User.Identity.IsAuthenticated)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)