views:

71

answers:

2

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  A: 

Try adding your code to this event in your ControllerBase:

protected override void Initialize(RequestContext requestContext){

}
Nik
+1  A: 

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.

StriplingWarrior