Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HttpContextAccessor in a .NET 4.6 project

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.

like image 241
Tom Avatar asked Jul 19 '16 12:07

Tom


People also ask

What is HttpContextAccessor .NET core?

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.

Is HttpContextAccessor thread safe?

As long as you inject HttpContextAccessor in your services - services being singleton or not - you'll be fine.

How do I get HttpContext in .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.


1 Answers

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.

like image 113
Andy-Delosdos Avatar answered Oct 10 '22 05:10

Andy-Delosdos