How To Use Sessions In ASP.NET Core

Introduction

In this article, you will learn how to use your C# coding prowess to set up the session state in your ASP.NET Core and MVC Core Web applications.

Create your core application

Step 1

Open Visual Studio and select File >> New Project.

The ”New Project” window will pop up. Select .NET Core and select “ASP.NET Core Web Application”. Name your project and click “OK”.

 

A "New Project" window will pop up. Select Web Application and click “OK”, as shown below.

Step 2

Once your project is ready, open Solution Explorer, right-click “dependencies”, and click “Manage NuGet Packages…”.

 

Packages Required

We need to install the stable version of “Microsoft.AspNetCore.Session” from the NuGet Package Manager. Then only we can access the session state in ASP.NET Core. Click on the “Install” button.

 

Step 3

Now, double click “HomeControllers.cs”. The following is an example of a session sharing in ASP.NET Core.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.AspNetCore.Http;  
  7. using Microsoft.AspNetCore.Mvc;  
  8. using Session_State.Models;  
  9.   
  10. namespace Session_State.Controllers  
  11. {  
  12.     public class HomeController : Controller  
  13.     {  
  14.   
  15.         const string SessionName = "_Name";  
  16.         const string SessionAge = "_Age";  
  17.         public IActionResult Index()  
  18.         {  
  19.             HttpContext.Session.SetString(SessionName, "Jarvik");  
  20.             HttpContext.Session.SetInt32(SessionAge, 24);  
  21.             return View();  
  22.         }  
  23.   
  24.         public IActionResult About()  
  25.         {  
  26.             ViewBag.Name = HttpContext.Session.GetString(SessionName);  
  27.             ViewBag.Age = HttpContext.Session.GetInt32(SessionAge);  
  28.             ViewData["Message"] = "Asp.Net Core !!!.";  
  29.   
  30.             return View();  
  31.         }  
  32.   
  33.         public IActionResult Contact()  
  34.         {  
  35.             ViewData["Message"] = "Your contact page.";  
  36.   
  37.             return View();  
  38.         }  
  39.   
  40.         public IActionResult Error()  
  41.         {  
  42.             return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });  
  43.         }  
  44.     }  
  45. }  

Step 4

Now, double click ”Startup.cs” to configure the services. The very first step we need to take is to add the session service to the container so that we can add the services in the “configureServices” function.

  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.      
  4.     services.AddDistributedMemoryCache();  
  5.     services.AddSession(options => {  
  6.         options.IdleTimeout = TimeSpan.FromMinutes(1);//You can set Time   
  7.     });  
  8.     services.AddMvc();  
  9. }  

Configure the HTTP Request Pipeline

Now, in the same class, we add “app.Usersession()” inside the “configure” function so that it gets called by the runtime.

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  2. {  
  3.     if (env.IsDevelopment())  
  4.     {  
  5.         app.UseDeveloperExceptionPage();  
  6.         app.UseBrowserLink();  
  7.     }  
  8.     else  
  9.     {  
  10.         app.UseExceptionHandler("/Home/Error");  
  11.     }  
  12.   
  13.     app.UseStaticFiles();  
  14.   
  15.     app.UseSession();  
  16.   
  17.     app.UseMvc(routes =>  
  18.     {  
  19.         routes.MapRoute(  
  20.             name: "default",  
  21.             template: "{controller=Home}/{action=Index}/{id?}");  
  22.     });  
  23. }  

Now, run your projec. You will see the output of an Active Session, as below.

 
Let us set “one” minute as the Session TimeOut in the “ConfigureServices” function of the “Startup.cs” class.
  1. services.AddSession(options => {  
  2.     options.IdleTimeout = TimeSpan.FromMinutes(1);//You can set Time   
  3. });  

Session Expires

 
That's it. I hope you have found this article helpful. Do let me know via comments and likes. 

Up Next
    Ebook Download
    View all
    Learn
    View all
    nothing