takayoshi
takayoshi

Reputation: 2799

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;
            }

Upvotes: 8

Views: 7528

Answers (2)

StriplingWarrior
StriplingWarrior

Reputation: 156524

Your controller gets constructed before the HttpContext has been set by ASP.NET. Like Nik says, you need to put this code into an overridden method in your class.

I would also point out that depending on HttpContext directly will make it impossible to perform unit testing on any of your controllers that extend this class. This is why many of the methods (like the Execute method) in the ControllerBase class take a RequestContext as an argument. You can say:

protected override void Execute(System.Web.Routing.RequestContext requestContext)
{
    var currentUser = requestContext.HttpContext.User;
    ...
}

... which makes it possible to create and execute your controllers with "fake" contexts for unit testing purposes.

Upvotes: 5

Nik
Nik

Reputation: 2726

Try adding your code to this event in your ControllerBase:

protected override void Initialize(RequestContext requestContext){

}

Upvotes: 11

Related Questions