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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With