Accessing HttpContext from a Class Library

JORGE MALDONADO BARRERA 211 Reputation points
2024-10-22T18:06:35.2066667+00:00

Hi,

I have a ASP.NET 8 project with a class library that contains my business objects. I need to access HttpContext in my class library to get information about the current user but I see that Microsoft.AspNetCore.Http is deprecated.

I have found several support articles but everything I have found also says it is deprecated.

How can I get access to HttpContext in a class library?

Best regards.

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-10-22T20:03:06.1966667+00:00

    Microsoft.AspNetCore.Http is not deprecated. Unlike webforms, there is no static access to HttpContext, you must pass it to object/methods that need it.

    but why would business objects need HttpContext access? they should just need the business models. you should just pass the application user to the objects. better yet, define your own BusinessObjectContext that has the properties required from a http request (user, request id, logging, etc). this context could be injected.

    if you inject the business object(s), they can easily also have injected objects.

    note: you should avoid using HttpContextAccessor as it has limitations and performance issues.

    0 comments No comments

  2. SurferOnWww 4,631 Reputation points
    2024-10-23T02:48:33.36+00:00

    How can I get access to HttpContext in a class library?

    The following Microsoft document will help:

    Access HttpContext from custom components

    Do not store IHttpContextAccessor.HttpContext in a field

    As for the performance issue of IHttpContextAccessor, there are several discussions such like IHttpContextScopedAccessor for accessing HttpContext from request scoped DI components. To my knowledge, however, there is no other solution than using IHttpContextAccessor to access the HttpContext from a class library.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.