Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I access the HttpContext from the Controller initializer?

I have a controller set up like this:

public class GenesisController : Controller
{

    private string master;
    public string Master { get { return master; } }

    public GenesisController()
    {
        bool mobile = this.HttpContext.Request.Browser.IsMobileDevice; // this line errors
        if (mobile)
            master="mobile";
        else
            master="site";
    }

}

All of my other controllers inherit from this GenesisController. Whenever I run the application, i get this error saying

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

How can I access HttpContext and from the controller initialization?

like image 373
quakkels Avatar asked Jul 27 '11 19:07

quakkels


People also ask

How can get HttpContext current in ASP.NET Core?

In ASP.NET Core, if we need to access the HttpContext in service, we can do so with the help of IHttpContextAccessor interface and its default implementation of HttpContextAccessor. It's only necessary to add this dependency if we want to access HttpContext in service.

What is HttpContext in asp net?

HttpContext is an object that wraps all http related information into one place. HttpContext. Current is a context that has been created during the active request. Here is the list of some data that you can obtain from it.

What is the use of IHttpContextAccessor?

The IHttpContextAccessor is an interface for . Net Core for accessing HttpContext property. This interface needs to be injected as dependency in the Controller and then later used throughout the Controller.


1 Answers

Because the HttpContext is not available in the controller constructor. You could override the Initialize method where it will be accessible, like this:

protected override void Initialize(RequestContext requestContext)
{
    base.Initialize(requestContext);
    bool mobile = this.HttpContext.Request.Browser.IsMobileDevice; // this line errors
    if (mobile)
        master="mobile";
    else
        master="site";
}

Also I bet that what you are trying to do with this master variable and booleans might be solved in a far more elegant way than having your controllers worry about stuff like this.

like image 179
Darin Dimitrov Avatar answered Oct 22 '22 02:10

Darin Dimitrov