Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the HttpContext in .Net 7 (as IHttpContextAccessor is deprecated)

I need to access the HttpContext from a custom component in a Asp.net Core WebApi app, and I found this page (under the point 'Access HttpContext from custom components'):

https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/fundamentals/http-context.md

The above page suggests the usage of IHttpContextAccessor and builder.Services.AddHttpContextAccessor(); registration.

This page seems to be updated (5 months ago), but if i want to use the IHttpContextAccessor then i have to add a reference to the Microsoft.AspnetCore.Http.Abstraction package. And this package is deprecated. I couldn't find any alternative package for .Net7.

How can i accesss the HttpContext properly?

like image 780
Benjamin Martin Avatar asked Dec 08 '25 10:12

Benjamin Martin


1 Answers

The IHttpContextAccessor is not deprecated, it is included in the Microsoft.AspNetCore.App shared framework.

If your project is dependent upon this framework, it should work out-of-the-box.

If you use Microsoft.NetCore.App (which I suspect) you have to add a reference in your .csproj file

<ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

Read more about it here

like image 63
benzok Avatar answered Dec 10 '25 01:12

benzok