Skip to content

Session in ASP.NET Core MVC

Session: A session is one of the most useful server-side state management techniques, used to store information for web pages. Each browser instance gets its own session. A single user can have multiple sessions by visiting your application from multiple browser instances on their machine, each with a different session ID.
Session is global data for a single user.

How to Implement Session in an ASP.NET Core Application

To implement session, we define the session keys and use the GetString and SetString methods to get and set session values in an ASP.NET Core application. Below are the code snippets and images for the session implementation.

Define two const variables, as shown in the code below, to use as session keys.

private const string UserName = "cs.sudhir@gmail.com";

        private const string Age = "37"; 
Controller storing and reading values in Session

As shown in the image above, you set session values using the SetString method and read them using the GetString method, as shown in the code below.

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 session values with SetString and reading them with GetString, register the session services with AddSession in the service collection in Program.cs, and define the session timeout using TimeSpan.FromMinutes(1). In our application, the session timeout is 1 minute; you can set it according to your requirements. You also need to add the UseSession middleware in Program.cs. Below is the image and code snippet for the session setup.

Configuring session services with a 1-minute timeout and UseSession in Program.cs
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 and reading the session values, I created a view to show them in the UI. Below is the view code, which reads the ViewBag values that hold the session data.

Razor view displaying the session values
Browser output showing the values read from Session

More About Session in ASP.NET Core

Session lets us store information in server memory. It can store any type of object, including our own custom objects.
Session data is stored separately for every client, which means session data is stored on a per-client basis.
As we know, HTTP is a stateless protocol: it cannot keep client information between pages. If a user enters some information and moves to the next page, that data is lost and the user cannot get it back. Session gives us a way to store that information.
State management using session is one of the best ASP.NET features, because it is secure, transparent to users, and we can store any kind of object in it.

Advantages of Session: the main advantages of Session are:

  • Session helps to maintain user state and data across the application.
  • Session is easy to implement, and we can store any kind of object in it.
  • Session stores data separately for each user.
  • Session is secure and transparent to users.

Disadvantages of Session: the main disadvantages of Session are:

  • Performance overhead with a large volume of data or users, because session data is stored in server memory and clients read the data from the server.
  • Overhead from serializing and deserializing session data, because in State Server and SQL Server modes the objects must be serialized before they are stored.

Session events in ASP.NET Web Forms: There are two session events available in ASP.NET Web Forms applications.

  • Session_Start
  • Session_End
We can handle both these events in the Global.asax file of a Web Forms application. When a new session starts, the Session_Start event is raised; when the session is abandoned or expires, the Session_End event is raised.
Removing sessions: The following methods remove session data in Web Forms applications:
  • Session.Remove("name"): removes one item from the session state collection.
  • Session.RemoveAll(): removes all items from the session collection.
  • Session.Clear(): removes all items from the session collection. There is no difference between the Clear and RemoveAll methods.
  • Session.Abandon(): cancels the current session.