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
To access session in non-controller class -
First, register the following service in Startup.ConfigureServices
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Now, register a class (example - SessionManager) where you want to access the Session in Startup.ConfigureServices.
services.AddScoped<SessionManager>();
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With