8

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

2 Answers 2

11

Try adding your code to this event in your ControllerBase:

protected override void Initialize(RequestContext requestContext){

}
1
  • 2
    I discovered that I needed to call base.Initialize(requestContext) inside this override otherwise I would get a NullReferenceException later. Commented Apr 15, 2013 at 18:34
5

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.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.