Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Current.User is null in ControllerBase(asp.net mvc)

I have a ControllerBase class in an ASP.NET MVC Application. The other controllers inherit from ControllerBase.

I want to access HttpContext.User.Identity.Name, but HttpContext is null. What's the matter?

public ControllerBase()
        {
            var dataManager=new DataManager();
            if (HttpContext.User.Identity.IsAuthenticated) // throws error
            {                    
                ViewData["assets"] = ud.BalanceFreeze + ud.Balance + ud.BalanceRealty;
                ViewData["onaccount"] = ud.Balance;
                ViewData["pending"] = ud.BalanceFreeze;
                ViewData["inrealty"] = ud.BalanceRealty;
            }
like image 378
takayoshi Avatar asked Sep 13 '10 20:09

takayoshi


People also ask

What is HttpContext current User identity?

It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.

Why HttpContext current is null?

It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with. Overall, don't use Application["Setting"] to store global stuffs, as they are not global as you discovered.

What is HttpContext in ASP NET MVC?

The HttpContext object constructed by the ASP.NET Core web server acts as a container for a single request. It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any.

How do you set HttpContext User identity for an application manually?

You can achieve this by manually settings HttpContext. User: var identity = new ClaimsIdentity("Custom"); HttpContext. User = new ClaimsPrincipal(identity);


1 Answers

Try adding your code to this event in your ControllerBase:

protected override void Initialize(RequestContext requestContext){

}
like image 99
Nik Avatar answered Oct 16 '22 03:10

Nik