I've created a .NET Core project (a class library) that also targets .NET 4.6, which needs to be able to access the current HTTP context. I see that we can no longer use the static HttpContext.Current
, and have to inject an instance of IHttpContextAccessor
. Is this something I can still use inside something like a Web API project targeting .NET 4.6? So far, I can't get HttpContextAccessor.HttpContext
to return anything but null.
It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any. ASP.NET Core applications access the HTTPContext through the IHttpContextAccessor interface. The HttpContextAccessor class implements it.
As long as you inject HttpContextAccessor in your services - services being singleton or not - you'll be fine.
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.
For the class library I think you might want to pass the relevant variables/objects via constructor or methods. It's good practice, because your class library wont break if you reference it in a console app without a httpcontext, for example.
If you're inside a controller method, you can just use Request or Response.
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