In previous post, we learned how to use Session in ASP.NET Core. In this article, we'll learn about Session Wrapper design pattern to ease the access of Session. In short, we'll make our access of session "Typed". Also, we may apply any validation or constraint in this wrapper class.
Step 1 - Create a Session Manager class
In this example, we are going to store two items in Session (i.e. ID & LoginName).
- We are injecting IHttpContextAccessor so that we can access the Session variable.
- We are creating properties which are actually accessing Session variable and returning the data or writing the data to Session.
- We have added one helping property "IsLoggedIn" which is using other properties to make a decision. We may have more such helping/wrapper properties.
- using Microsoft.AspNetCore.Http;
- public class SessionManager
- {
- private readonly ISession _session;
- private const String ID_KEY = "_ID";
- private const String LOGIN_KEY = "_LoginName";
- public SessionManager(IHttpContextAccessor httpContextAccessor)
- {
- _session = httpContextAccessor.HttpContext.Session;
- }
-
- public int ID
- {
- get
- {
- var v = _session.GetInt32(ID_KEY);
- if (v.HasValue)
- return v.Value;
- else
- return 0;
- }
- set
- {
- _session.SetInt32(ID_KEY, value);
- }
- }
- public String LoginName
- {
- get
- {
- return _session.GetString(LOGIN_KEY);
- }
- set
- {
- _session.SetString(LOGIN_KEY, value);
- }
- }
- public Boolean IsLoggedIn
- {
- get
- {
- if (ID > 0)
- return true;
- else
- return false;
- }
- }
- }
Step 2
Registering IHttpContextAccessor and SessionManager in Startup file.
- services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
- services.AddScoped<SessionManager>();
Step 3
Injecting SessionManager in your classes. Here is an example of Controller class but in the same way, it can be injected in non-controller classes too.
- private readonly SessionManager _sessionManager;
- public HomeController(SessionManager sessionManager)
- {
- _sessionManager = sessionManager;
- }
Step 4
Using SessionManager to access Session Data,
- _sessionManager.ID = 1;
- _sessionManager.LoginName = dto.Login;
- if(_sessionManager.IsLoggedIn == true)
- {
- ViewBag.Login = _sessionManager.LoginName;
- return View();
- }
Conclusion
This wrapper pattern helps using Session without worrying about KeyNames & Makes access easier. It also helps you apply different conditioning and constraints in a wrapper class.