Search code examples
c#asp.net-corehttpcontext

Is there a way for a simple way for ClassLibrary to get Session Value?


I have an external ClassLibrary Project that needs to get session value set from HomeController in the Main Project. Is there a simple way to accomplish this?

Or is there an alternative to transfer a value from HomeController to an external ClassLibrary?


Solution

  • You can use the IHttpContextAccessor class

    For other framework and custom components that require access to HttpContext, the recommended approach is to register a dependency using the built-in dependency injection container. The dependency injection container supplies the IHttpContextAccessor to any classes that declare it as a dependency in their constructors.

    public void ConfigureServices(IServiceCollection services)
    {
         services.AddMvc()
             .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
         services.AddHttpContextAccessor();
         services.AddTransient<IUserRepository, UserRepository>(); 
    }
    

    In the following example:

    • UserRepository declares its dependency on IHttpContextAccessor.
    • The dependency is supplied when dependency injection resolves the dependency chain and creates an instance of UserRepository.

    .

    public class UserRepository : IUserRepository
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
    
        public UserRepository(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
    
        public void LogCurrentUser()
        {
            var username = _httpContextAccessor.HttpContext.User.Identity.Name;
            service.LogAccessRequest(username);
        }
    }
    

    Don't forget to add services.AddHttpContextAccessor(); to make the dependency injection work.