Session State In ASP.NET Core And MVC Core

Introduction
 
In this article, we will explain how to create a "Session State in ASP.NET Core and MVC Core"
 
Session State
 
In Session State, we can use to save and store user data while the user browses your web app. We already know that in previous versions of ASP.NET, we could store session as key value pair like this "Session["Name"] = "Rajeesh Menoth"" and implement it in an easy way. But in the latest version of ASP.NET or ASP.NET Core, we need to do a few configurations for accessing and enabling Session State in the application. The main purpose of session is maintaining user data in memory because of HTTP is a stateless protocol.
 
Before reading this article, you must read the articles given below for ASP.NET Core knowledge.
Package Required
 
We need to install the stable version of “Microsoft.AspNetCore.Session” from Nuget Package Manager. Then only we can access Session State in ASP.NET Core 1.1.
 
 
 
.csproj
 
In “.csproj” we can check all the installed packages and versions details in ASP.NET Core 1.1.
  1. <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />  
  2.     <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />  
  3.     <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />  
  4.     <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.2" />  
  5.     <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />  
  6.     <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />  
  7.     <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />  
Assemblies Required
 
These are the assemblies mainly required for accessing functionality of Session State, MVC, JSON, etc
  1. using System;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using Microsoft.AspNetCore.Http;  
  4. using Newtonsoft.Json;  
Home Controller
 
The following code is the example of sharing session in ASP.NET Core 1.1.
  1. using System;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using Microsoft.AspNetCore.Http;  
  4. using Newtonsoft.Json;  
  5.    
  6. namespace SessionInCore.Controllers  
  7. {  
  8.     public class HomeController : Controller  
  9.     {  
  10.         const string SessionKeyName = "_Name";  
  11.         const string SessionKeyAge = "_Age";  
  12.         const string SessionKeyDate = "_Date";  
  13.    
  14.         public IActionResult Index()  
  15.         {  
  16.             HttpContext.Session.SetString(SessionKeyName, "Rajeesh Menoth");  
  17.             HttpContext.Session.SetInt32(SessionKeyAge, 28);  
  18.             // Requires you add the Set extension method mentioned in the SessionExtensions static class.  
  19.             HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);  
  20.    
  21.             return View();  
  22.         }  
  23.    
  24.         public IActionResult About()  
  25.         {  
  26.             ViewBag.Name = HttpContext.Session.GetString(SessionKeyName);  
  27.             ViewBag.Age = HttpContext.Session.GetInt32(SessionKeyAge);  
  28.             ViewBag.Date = HttpContext.Session.Get<DateTime>(SessionKeyDate);  
  29.    
  30.             ViewData["Message"] = "Session State In Asp.Net Core 1.1";  
  31.    
  32.             return View();  
  33.         }  
  34.    
  35.         public IActionResult Contact()  
  36.         {  
  37.             ViewData["Message"] = "My Contact Details";  
  38.    
  39.             return View();  
  40.         }  
  41.    
  42.         public IActionResult Error()  
  43.         {  
  44.             return View();  
  45.         }  
  46.            
  47.     }  
  48.    
  49.     public static class SessionExtensions  
  50.     {  
  51.         public static void Set<T>(this ISession session, string key, T value)  
  52.         {  
  53.             session.SetString(key, JsonConvert.SerializeObject(value));  
  54.         }  
  55.    
  56.         public static T Get<T>(this ISession session, string key)  
  57.         {  
  58.             var value = session.GetString(key);  
  59.             return value == null ? default(T) :  
  60.                                   JsonConvert.DeserializeObject<T>(value);  
  61.         }  
  62.     }  
  63. }  
The following code contains the Key name as "SessionKeyName" & Value name as "Rajeesh Menoth". So we can set the Session String "Key" and "Value" in SetString("Key","Value").
  1. const string SessionKeyName = "_Name";  
  2. HttpContext.Session.SetString(SessionKeyName, "Rajeesh Menoth");  
The following code contains a similar Session code as an older version of ASP.NET.
  1. Session["Name"] = "Rajeesh Menoth";  
We can Assign and Get the Session string value using "GetString(Name)" Method in a simple way.
  1. ViewBag.Name = HttpContext.Session.GetString(SessionKeyName);  
In the following way we can set and get serializable objects to Session in our application.
  1. //Accessing Extension Method.  
  2. HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);  
  3. //Example of Extension Method.  
  4.  public static class SessionExtensions  
  5.     {  
  6.         public static void Set<T>(this ISession session, string key, T value)  
  7.         {  
  8.             session.SetString(key, JsonConvert.SerializeObject(value));  
  9.         }  
  10.    
  11.         public static T Get<T>(this ISession session, string key)  
  12.         {  
  13.             var value = session.GetString(key);  
  14.             return value == null ? default(T) :  
  15.                                   JsonConvert.DeserializeObject<T>(value);  
  16.         }  
  17.     }  
Configure Services
 
The first step is we need to add the Session services to the container. So we can add the services in "ConfigureServices" method in "Startup.cs" class in our application.
  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             //In-Memory  
  4.             services.AddDistributedMemoryCache();  
  5.             services.AddSession(options => {  
  6.                 options.IdleTimeout = TimeSpan.FromMinutes(1);  
  7.             });                
  8.             // Add framework services.  
  9.             services.AddMvc();  
  10.         }  
Configure the HTTP request pipeline
 
We add the "app.UseSession()" inside the Configure Method in "Startup.cs" Class because it gets called by the runtime. One more advantage is we can use this method to configure the HTTP request pipeline in our application.
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  2.         {  
  3.             loggerFactory.AddConsole(Configuration.GetSection("Logging"));  
  4.             loggerFactory.AddDebug();  
  5.    
  6.             if (env.IsDevelopment())  
  7.             {  
  8.                 app.UseDeveloperExceptionPage();  
  9.                 app.UseBrowserLink();  
  10.             }  
  11.             else  
  12.             {  
  13.                 app.UseExceptionHandler("/Home/Error");  
  14.             }  
  15.    
  16.             app.UseStaticFiles();  
  17.    
  18.             app.UseSession();  
  19.    
  20.             app.UseMvc(routes =>  
  21.             {  
  22.                 routes.MapRoute(  
  23.                     name: "default",  
  24.                     template: "{controller=Home}/{action=Index}/{id?}");  
  25.             });  
  26.         }  
OutPut – Active Session
 
 
 
OutPut – Session Expired
 
We set 1 mins as the Session Timeout in "ConfigureServices" method in Startup.cs class.
  1. services.AddSession(options => {  
  2.                options.IdleTimeout = TimeSpan.FromMinutes(1);//Session Timeout.  
  3.            });  
 
Reference
See Also
 
You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.
Conclusion
 
We learned how to create Session State In ASP.NET Core and MVC Core. I hope you liked this article. Please share your valuable suggestions and feedback.

Up Next
    Ebook Download
    View all
    Learn
    View all