Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core Use Session in Class

I am using Session in .Net core, However i am able to set and get the Session data in Controller like

HttpContext.Session.SetString("User", "True");
var user = HttpContext.Session.GetString("User");

But when i am trying to use the same code in a concrete class i am not able to do so. It does not show GetString or SetString after HttpContext.Session.

It does not work after

HttpContext.Session

Please help Thanks

like image 742
abhishek Avatar asked May 23 '18 09:05

abhishek


2 Answers

To access session in non-controller class -

  1. First, register the following service in Startup.ConfigureServices

      services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 
    
  2. Now, register a class (example - SessionManager) where you want to access the Session in Startup.ConfigureServices.

      services.AddScoped<SessionManager>(); 
    
  3. Now, in SessionManager class, add the following code.

      private readonly IHttpContextAccessor _httpContextAccessor;    
      private readonly ISession _session;    
      public SessionManager(IHttpContextAccessor httpContextAccessor)    
      {    
             _httpContextAccessor = httpContextAccessor;    
             _session = _httpContextAccessor.HttpContext.Session;    
       }  
    

The above code is receiving IHttpContextAccessor object through dependency injection and then, it is storing Sessions in a local variable.

like image 177
shalitha senanayaka Avatar answered Oct 08 '22 10:10

shalitha senanayaka


That's because HttpContext is a member of Controller, and outside a controller, it's a type name. See Access the current HttpContext in ASP.NET Core how to inject the IHttpContextAccessor into a class and access the session from there.

However, it's generally inadvisable to use the session in a class library. You'd better pass the particular values to your library call. So instead of accessing the settings in the library method, you do:

// controller code

var user = HttpContext.Session.GetString("User");
var libraryResult = _fooLibrary.Bar(user);
HttpContext.Session.SetString("UserResult", libraryResult);
like image 45
CodeCaster Avatar answered Oct 08 '22 10:10

CodeCaster