(C# ASP.NET Core) How to use Session for State Management

This article explains behind-the-scenes mechanism by which "Session" is implemented in ASP.NET Core. We also enumerate the four extension methods that ASP.NET Core provides for reading and writing session variables. After that we present a walkthrough where existence of a Session key is checked to conditionally show a login link, or to show her user-name along with a log-off link that clears the user-name from the Session cache.
(Rev. 18-Jun-2024)

Categories | About |     |  

Parveen,

What is a Session?

In nutshell: a session is used to store user data in key-value format till a user browses the pages of your app, i.e., till he stays in a "browsing session".

Session is not enabled by default in an ASP.NET Core application. An app must specifically enable it for availability, as explained later in this article.

When a browser requests a page of your app for the first time, a session cookie is created, and a unique session identifier is stored in it.

The session cookie + session id is used to identify future requests from the same browser. This allows ASP.NET to store small amounts of data on the server side, and make it available for subsequent requests. A typical use of session variables is to store the display name of a logged-in user and keep showing it at the top of various pages as she continues to browse your website.

The data held for one user doesn't mix with that for another because of the unique session id.

The browser holds the session cookie in memory, hence it is cleared away on exit; and also if the browser remains idle for a certain timeout. This period can be configured as explained later in this article.

How to Create and Read Session Variables?

ASP.NET Core provides extension methods for storing string and int type of data in Session variables on the server side. Each session variable is accessed through a "key", which is a string of any readable name.

Following code stores a string called "hello session" with the key "SESS_1", and an int with a key called "SESS_2"

// string to be stored 
String data = "hello session";

// the extension method to use 
HttpContext.Session.SetString("SESS_1", data);

// store an int 
HttpContext.Session.SetInt32("SESS_2", 65);

Following code extracts the data we saved above.

// the extension method to read a string 
String s = HttpContext.Session.GetString("SESS_1");

// the extension method to read an int 
int i = HttpContext.Session.GetInt32("SESS_2");

Video Explanation with a Working Example

Please watch the following youtube video:

Objective of this Walkthrough?

The user sees a page with a link to login. No input boxes are shown, to keep the things simple.

When the link is clicked, a login takes place through a dummy process and a user-name called "XYZ" is saved in a session variable [of key "SKEY"] and the response is redirected to the same page. Upon redirection, Session contains the key ["SKEY"], which is used to read the stored user-name, and "You are logged in as XYZ" is displayed.

The page also shows a link for log off. When the user clicks that link, the session key is removed, and the user again sees the link to login.

Step 1 of 4: Create an ASP.NET Core Project
(see the linked video for details)

Create a simple ASP.NET Core project with just one razor page called Index. You will have two files for this - Index.cshtml and Index.cshtml.cs

Step 2 of 4: Configure the use of Session

Come to the Startup.cs file and make these two additions.

ConfigureServices method: add support for session as shown below.

public void ConfigureServices(IServiceCollection services)
{

  // add support for razor pages 
  services.AddRazorPages();

  services.AddSession(options =>
  {

    // default session time out is 20 minutes 
    // but we can set it to any time span 
    options.IdleTimeout = TimeSpan.FromMinutes(30);

    // allows to use the session cookie 
    // even if the user hasn't consented 
    options.Cookie.IsEssential = true;

  });

}

Configure method: Add session middleware to the pipeline. A call to UseSession is added as shown below.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{

  if (env.IsDevelopment())
  {

    app.UseDeveloperExceptionPage();

  }

  app.UseRouting();

  // allow to manage user session data 
  app.UseSession();

  app.UseEndpoints(endpoints =>
  {

    endpoints.MapRazorPages();

  });

}

}

Step 3 of 4: Index.cshtml.cs backing class
(see the linked video for details)

Complete the backing class as shown below.

public void OnGet(): this method is called when the user requests your page for the first time. Session variable [of key "SKEY"] is read and the value is stored in a property called String UserName. If no such variable exists then UserName will contain null. This property is used in the razor page in Step 4 next.

public IActionResult OnGetDoLogin(): this event handler is for the login link [see the razor page next]. Actual login process is avoided to keep this tutorial focussed. So it is assumed that some dummy login process takes place and a user of name "XYZ" has logged in. This user-name is saved in Session with a key "SKEY".

public IActionResult OnGetLogOff(): this event handler is for the log-off link [see the razor page next]. It clears away the Session key.

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.RazorPages;

using System;

namespace MySession.Pages
{

  public class IndexModel : PageModel
  {

    // a string for the session key 
    // this will prevent bugs due to 
    // bad typing 
    internal const string SESS_KEY = "SKEY";

    // holds user-id after reading 
    // a session variable 
    public String UserName { get; set; }

    // when the index page is requested 
    public void OnGet()
    {

      // will be null if no session variable 
      UserName = HttpContext.Session.GetString(SESS_KEY);

    }

    // when the link to login is clicked 
    // click event handlers are prefixed 
    // OnGet or OnPost depending on the 
    // type of request they handle 
    public IActionResult OnGetDoLogin()
    {

      // let us say some dummy login process 
      // takes place and gives us the user 
      // name as XYZ 

      // save in a session 
      HttpContext.Session.SetString(SESS_KEY, "XYZ");

      return RedirectToPage();

    }

    // when the link to log off is clicked 
    public IActionResult OnGetLogOff()
    {

      // remove session key 
      HttpContext.Session.Remove(SESS_KEY);

      return RedirectToPage();

    }

  }

}

Step 4 of 4: Index.cshtml Razor markup Page
(see the linked video for details)

An if condition checks if the UserName property is set and shows the message "You are logged in as XYZ", otherwise it presents a login link that binds to the public IActionResult OnGetDoLogin() method in the backing class.

@page "{handler?}"

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@model MySession.Pages.IndexModel

<div style="width:75%;margin:1em auto;text-align:center">

  @if (String.IsNullOrEmpty(Model.UserName))
  {

    <a asp-page-handler="DoLogin">Login</a>

  }
  else
  {

    <span>
      You are logged in as @Model.UserName
    </span>

    <br />

    <a asp-page-handler="LogOff">LogOff</a>

  }

</div>


This Blog Post/Article "(C# ASP.NET Core) How to use Session for State Management" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.