Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User is Null in controller but in View has Value

I use ASP.NET MVC 5 and Identity for Authentication , My problem is with belowe code :

User.Identity.IsAuthenticated

User is Null , but I used Above code in View Like belowe and its work fine and user has Value .

  @if (User.Identity.IsAuthenticated)
            {...}

what is matter ?

to do this I search on google and find a way with

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);
    }
like image 311
Uthman Rahimi Avatar asked Jan 06 '23 08:01

Uthman Rahimi


1 Answers

I suspect that you are trying to call this method inside the constructor of a controller. This constructor is called too early in the HTTP request execution pipeline and the HttpContext is not available there. You can access the HttpContext inside the Initialize method:

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

    // Now you can access the HttpContext and User
    if (User.Identity.IsAuthenticated)
    {
        ...
    }
}
like image 92
Darin Dimitrov Avatar answered Jan 14 '23 06:01

Darin Dimitrov