Session in ASP.NET Core MVC

Session :- A Session is one of the most useful Server Side State Management technique used for store information of web pages. A Session is a Unique Instance of the browser. A Single user can have multiple sessions , by visiting your application with multiple instances of the browser running with a different Session ID on his machine.
Session is Single User Global data.

How to Implement Session in ASP.Net Core Application ?

To Implement session we need to define the session variable and using the GetString and SetString methods we can get and set the sessions in asp core application. Below is the attached code snippet and images for session implementation with details.

Define two const variables as shown in below code that we will use as a seesion variables.

                
private const string UserName = "cs.sudhir@gmail.com";
        private const string Age = "37"; 
                
Image is not available

As explain in above image you can set the session variables values using the SetString mthod and get the values using the GetString methods as shown in below code.

                
  public IActionResult Index()
        {
            HttpContext.Session.SetString(UserName, "Sudheer Singh Chouhan");
            HttpContext.Session.SetInt32(Age, 40);
            return View();
        }       
                
                
 public IActionResult Privacy()
        {
            ViewBag.Name = HttpContext.Session.GetString(UserName);
            ViewBag.Age =HttpContext.Session.GetInt32(Age);
            return View();
        }       
                

After setting up the session variables using SetString and Get the Session variables using the GetString methods you need to register AddSession Services into the services collection of program.cs file and define the Session Timeout for application using TimeSpan.FromMinutes(1) . In our application I have set the Session Timeout for 1 Minute only you can set according to your requirements. Further you need to use UseSession Miidileware in program.cs file for Session Implementation. Below is the image and code snippet for Session.

Image is not available
                
using MiddileWareExample.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.

builder.Services.AddControllersWithViews();
builder.Services.AddSession(option => option.IdleTimeout=TimeSpan.FromMinutes(1));
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseSession();
app.UseRouting();

app.UseAuthorization();
app.UseCheckUrlValidations();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Privacy}/{id?}");

app.Run();      
                

After setting up and getting up the Session , here I have created a view for representing this in UI.
Below is the code for view to get viewbag variables that we have used for Session data to present on UI.

Image is not available
Image is not available
More About the Session in ASP.Net Core

Session provides facility to store information on Server Memory.It can support any type of Object to store alongwith our own custom objects.
For every Client , Session data is Stored seperately , which means session data is stored on a per Client basis.
As we all know ,HTTP is a Stateless Protocol , it can not hold client information on a page , if user insert some information and move to the next page, that data will be lost and the user would not be able to retrieve that information, so need to store information Session provides these facilities to us.
State Management using Session is one of the best ASP.NET feature because it is Secure, Transparent from Users and we can Store any kind of Object in it.

Advantages of Session : Following are some advantages of Session-

  • Session helps to maintain User State and data over the application.
  • Session is Easy to implement and we can Store any kind of object in it
  • Session Stores data seperately
  • Session is Secure and Transparent from the Users.

Disdvantages of Session : Following are some Disadvantages of Session,

  • Performance overhead in case of large volume of data/user , because Session data is stored in Server Memory and Clients read data from the Server.
  • Overhead involved in Serialization and Deserialization of Session data because in the case of State Server and Sql Server modes, we need to Serialize the Objects before storing them.

Session Events in ASP.NET Web Forms: There are two types of Session Events avialble in ASP.NET Web Forms Applications.

  • Session_Start
  • Session_End
We can handle both these events in the Global.asax file of our Web Forms application. When a new Session initiates the Session_Start event is raised, when the Session is Abandoned or expires Session_End event raised.
Removing Sessions : There are some list of methods that are used to remove Session in Web Forms Applications.
  • Session.Remove(sessionvariable name is here) : It removes an item from the Session State Collection.
  • Session.RemoveAll() :- Removes all items from the Session Collection.
  • Session.Clear() :- Remove all items from session collection .there is no difference between Clear and RemoveAll methos
  • Session.Abandon() :- Cancels the Current Session.


Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.