Tom
Tom

Reputation: 1581

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.

Upvotes: 8

Views: 5354

Answers (1)

Andy-Delosdos
Andy-Delosdos

Reputation: 3720

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.

Upvotes: 2

Related Questions