How do I access the HttpContext from the abstract base controller?

I created an abstract controller class ( ApplicationController

) to handle some custom authentication, but it HttpContext

doesn't initialize when the code is called.

public abstract class ApplicationController : Controller
{
    public ApplicationController()        
    {
        string myuser = HttpContext.User.Identity.Name; // NullReferenceException
    }
}

      

+2


source to share


2 answers


Yassir is correct about the use of protected constructors in abstract classes. But you're right that it doesn't solve your problem - the HttpContext is still not populated, but you are getting null reference exceptions.

Anyway, the solution is simple - override the controller's Initialize method:



protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    string myuser = this.User.Identity.Name;
    base.Initialize(requestContext);
}

      

+3


source


try to make yours protected.

public abstract class ApplicationController : Controller 
{
    protected ApplicationController()
    {
        string myuser = this.User.Identity.Name;
    } 
}

      



also make sure you don't miss it with the directive:

using System.Web.Mvc;

      

0


source







All Articles