Skip to main content

.Net Core Session Management

The Session helps to store user data in the application memory. Since the user data stores on the application it quick and fast to access. .Net Core Session data stored application using the cache, this cache can be either In-Memory or Distributed Cache. 

Session Work-flow:

  • On the user request the application from the browser, the server will create a session with an id called Session-Id. 
  • This Session-Id will be given to the user in response by storing it in the cookie. So on every next request, this cookie will reach to the application which contains Session-Id. 
  • An application uses the SessionId as the main key and stores all user data in the application cache. So by receiving a cookie from a client with Session-Id application will fetch the session stored data as per request. 
  • This cookie session is browser-specific it is not sharable between browsers. 
  • We can set session time out in our application, where after the time session data will get automatically cleared.

Create A Sample .Net Core MVC Application:

Let's create a sample MVC application to get hands-on for implementing and configuring the session in the application. To create a .Net Core MVC application you can use either Visual Studio 2019(Support .Net Core 3.0 +) or Visual Studio Code. Click here to understand the visual studio code to create a .Net Core Application.

Register Session:

Now register session service in application startup file as follows.
Startup.cs:(Inside of ConfigureService Method)
services.AddSession(options => {
	options.IdleTimeout = TimeSpan.FromMinutes(1);
	options.Cookie.HttpOnly = true;
	options.Cookie.IsEssential = true;
IdleTimeout - The IdleTimeout indicates how long the session can be idle before its content is abandoned. Each time session access will reset the timeout. This IdleTimeout only applies to session content on the server, not to the cookie which holds the session-id.
Cookie - The Cookie provides configuration for the cookie used to store the session-id.

Configure Session Middleware:

Now configure the session middleware in the startup file. It should be configured between the middleware like 'app.UseRouting()' and 'app.UseEndpoint()'.
Startup.cs:(Inside of Configure Method):




Check Session-Id:

We can check the Session-Id value from the 'HttpContext.Session.Id' as follows.
using Microsoft.AspNetCore.Mvc;
namespace SessionMvc.App.Controllers

    public class TestController:Controller
        public IActionResult GetSessionId()
            return Content(HttpContext.Session.Id);

From the picture above we fetched Session-Id created by the application. But we can observe the session cookie was not created. The reason behind the session cookie not created, the application only stores the session on at least single user data to be stored in the session. So in this case, if the user requested application multiple times, on every request application creates a new session-id, since there was no session cookie.

Store And Fetch Data From Session:

Till now we haven't set and fetch data from the session. So to do that we have some predefined methods to set and fetch session data as follows.

'HttpContext.Session.Set(string key, byte[] value)' - In this, we need to pass one parameter like 'key' which of type string used for fetch stored data, and another parameter of type byte[](byte array) which our actual data to be stored in the session.
'HttpContext.Session.TryGetValue(string key, out byte[] value)' - In this, we need to pass a key-value to fetch the data stored in the session. Here it outputs the value as bytep[](byte array).

Here to save or fetch data we need to deal with a byte array of data. So to make communication easy and simple .Net provide extension method under 'Microsoft.AspNetCore.Http' library.

'HttpContext.Session.SetString(string key, string value)' - In this method both key and value(data to be stored) of type string.
'HttpContext.Session.GetString(string key)' - In this method on passing key, we get session stored data as of type string.

using Microsoft.AspNetCore.Http;

namespace SessionMvc.App.Controllers
    public class TestController : Controller
        public IActionResult SaveToSession(string name)
            HttpContext.Session.SetString("your_name", name);
            return Content($"{name} save to session");

        public IActionResult FetchFromSession()
            string name = HttpContext.Session.GetString("your_name");
            return Content(name);

On saving data to the session, the application adds the session id to cookie and return to the response, so on every next request application uses the session id to fetch the data from the session store until the data expired.

Fetching stored data looks as below.

Store Objects In Session:

Session storage follows the key-value pair dictionary process to save or fetch data. In this process, we have only available methods to store data either in form byte[](byte array) or string, there is no overloaded method to save object or class or entity of data directly into the session.

So to store the Objects in session let's implement custom extension methods as follows.
using System.Text.Json;
using Microsoft.AspNetCore.Http;

namespace SessionMvc.App.Utilities
    public static class SessionExtension
        public static void Set<T>(this ISession session, string key, T value)
            session.SetString(key, JsonSerializer.Serialize(value));

        public static T Get<T>(this ISession session, string key)
            var value = session.GetString(key);
            return value == null ? default : JsonSerializer.Deserialize<T>(value);
Here we can observe serializing the object to string type and saved it using existing methods like 'ISession.SetString(string key, string value)'.

So to test these extension methods, let's create a model and try to store it in session as follows.
public class InfoModel
	public string Name { get; set; }
	public int Age { get; set; }
	public string Designation { get; set; }
Let's update our controller code as follows.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SessionMvc.App.Models;
using SessionMvc.App.Utilities;

namespace SessionMvc.App.Controllers

    public class TestController : Controller
        public IActionResult SaveToSession()
            var info = new InfoModel
                Name = "Naveen",
                Age = 26,
                Designation = ".NET Developer"
            HttpContext.Session.Set<InfoModel>("info", info);
            return Content($"save to session");

        public IActionResult FetchFromSession()
            InfoModel info = HttpContext.Session.Get<InfoModel>("info");
            return Content($"{info.Name} info fetched from session");

Clear Session:

'HttpContext.Session.Remove(string key)' - This method removes the given key from the session.

'HttpContext.Session.Clear()' - This method removes the all entries from the session.

Session Using SQL Distributed Cache:

For single-server applications saving session data in-memory of the application will work without any issue. But if an application hosted on multiple servers or nodes using then there is a chance of inconsistency with the application because the in-memory session is specific to the application which runs on a specific server, this in-memory can't be shared between multiple server or nodes.

So it is recommended to use DistributedCache to store the session data. We can use some of the DistributeCache stores like 'Redis', 'SQL Cache', 'NCache', etc. Here we going to use SQL cache to store the session data. Click here to know more about the Distributed SQL Cache, so here I'm going to show code snippet of SQL cache.

Let's install the following nugget to support the .NET Core SQL Cache.
.Net Core CLI Command:
dotnet add package Microsoft.Extensions.Caching.SqlServer
Click here to find the SQL script to generate the cache table.

Now to store the session data in the cache table we need to register SQL distributed service in the startup file.
services.AddDistributedSqlServerCache(options => {
	options.ConnectionString = Configuration.GetConnectionString("MyWorldDbConnection");
	options.SchemaName = "dbo";
	options.TableName = "MyCache";
	//options.ExpiredItemsDeletionInterval = TimeSpan.FromMinutes(6);
Configure your database connection string in appSettings.json.

That's all the configuration need to set up the SQL cache table and now run the application and check the session store in the cache table as follows.

Wrapping Up:

Hopefully, this article will help to understand the Session Management in .Net Core. I love to have your feedback, suggestions, and better techniques in the comment section.

Follow Me:


Popular posts from this blog

Endpoint Routing In Asp.Net Core

How Routing Works In  Core 2.1 And Below Versions?: In Asp.Net Core routing is configured using app.UseRouter() or app.UseMvc() middleware. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); Here in Dotnet Core version 2.1 or below versions on the execution of route middleware request will be navigated appropriate controller matched to the route.

An operation or functionality which is dependent on route URL or route values and that need to be implemented before the execution of route middleware can be done by accessing the route path from the current request context as below
app.Use(async (context, next) => { if(context.Request.Path.Value.IndexOf("oldvehicle") != -1) { context.Response.Redirect("vehicle"); } else { await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "vehicleRoute", template: "vehicle", defaults:new { …

GraphQL API Integration In Asp.Net Core Application

GraphQL is a query language for your API and a server-side runtime for executing queries by using a type system you define for your data. GraphQL can be integrated into any framework like ASP.NET, Java, NestJs, etc and it isn't tied to any specific database or storage engine and is instead backed by your existing code and data.
How GraphQL API Different From Rest API: GraphQL exposes a single end-point or route for the entire application, regardless of its responses or actions.HTTP-POST is the only Http verb recommended by the GraphQL.The client applications (consumers of API) can give instructions to GraphQL API about what type of properties to be returned in the response. Building Blocks Of GraphQL API:The main building blocks of GraphQL API is Schemas and Types. A 'Schema' in GrpahQL API describes the functionality available to the clients connect to API. Schema mostly consists of GraphQL Object Types, Queries, Mutations, etc.Types likely to be called Grap…

ASP.NET Core Web API Versioning

Introduction: An iteration and evolutionary changes of an ASP.NET Core Web API is handled by Versioning. Versioning of an API gives confidence to the clients which consumes API for a long time. Any changes or development of an API will be accessible using the new version and it won't cause issues to the clients consuming the old version of API.
When To Use Versioning:Any API response changes.Developing an API by implementing testing levels like 'Alpha', 'Beta', and 'RC' versions before releasing Production.Deprecating an API which means API going to be removed or upgraded by a version within a short period. Versioning Types:Query String VersioningUrl Path VersioningMedia Type Versioning API Version Nuget: To Configure versioning to AspNet Core Web API Microsoft provided a library(Microsoft.AspNetCore.Mvc.Versioning). So to use the versioning library please install NuGet below.
 Install-Package Microsoft.AspNetCore.Mvc.Versioning -version 4.0.0 Register API V…

.NET Core MVC Application File Upload To Physical Location With Buffered Technique

Buffering Technique In File Upload:The server will use its Memory(RAM) or Disk Storage to save the files on receiving a file upload request from the client. Usage of Memory(RAM) or Disk depends on the number of file requests and the size of the file. Any single buffered file exceeding 64KB is moved from Memory to a temp file on disk. If an application receives heavy traffic of uploading files there might be a chance of out of Disk or RAM memory which leads to crash application. So this Buffer technique used for small files uploading. In the following article, we create a sample for the file uploading using .NET Core MVC application.
Create The .NET Core MVC Project: Let's create a .NET Core MVC project, here for this sample I'm using Visual Studio Code as below.  Check the link to use the Visual Studio Code for .NET Core Application.
IFormFile: Microsoft.AspNetCore.Http.IFormFile used for file upload with buffered technique. On uploading files from the client, then the entire …

Ionic Picker Sample Code In Angular

Introduction: Ionic Picker(ion-picker) is a popup slides up from the bottom of the device screen, which contains rows with selectable column separated items.
The main building block of ion-picker as follows: PickerControllerPickerOptions PickerController: PickerController object helps in creating an ion-picker overlay. create(opts?: Opts): Promise<Overlay> PickerController create method helps in create the picker overlay with the picker options
PickerOptions: PickerOptions is a configuration object used by PickerController to display ion-picker.
Single Column Ionic Picker: single.item.picker.ts: import { Component } from "@angular/core"; import { PickerController } from "@ionic/angular"; import { PickerOptions } from "@ionic/core"; @Component({ selector: "single-column-picker", templateUrl:"single.item.picker.html" }) export class SingleItemPicker { animals: string[] = ["Tiger", "Lion", "Elephant"…

Blazor WebAssembly Dynamic Form Validation

Introduction: In Blazor WebAssembly(client-side framework) form validation can be done with Data Annotations. Using Data Annotations we can validate form either by default validation attributes or by creating custom validation attributes. Using this Data Annotation attribute we can dynamically add or remove validation on a specific field in a form.
Create Blazor WebAssembly Project: To create a Blazor WebAssembly template project need to install the latest version of VisualStudio 2019 for rich intelligence support or we can use VisualStudio code but less intelligence support from the editor. Click here to know about Blazor WebAssembly template creation. Blazor WebAssembly is in preview mode, not yet ready for production.
Create Razor Component: After creating a sample project using the Blazor WebAssembly template, in "Pages" folder add new Razor Component, name it as "UserForm.razor"
Add Route: In Blazor routing can be configured using @page  directive, and URL should b…

Asp.Net Core MVC Form Validation Techniques

Introduction: Form validations in any applications are like assures that a valid data is storing on servers. All programing frameworks have their own individual implementations for form validations. In Dotnet Core MVC application server-side validations carried on by the models with the help of Data Annotations and the client-side validations carried by the plugin jQuery Unobtrusive Validation. jQuery Unobtrusive Validation is a custom library developed by Microsoft based on the popular library jQuery Validate.
In this article, we are going to learn how the model validation and client-side validation works in Asp.Net Core MVC Application with sample examples.
Getting Started: Let's create an Asp.Net Core MVC application project using preferred editors like Microsoft Visual Studio or Microsoft Visual Studio Code. Here I'm using Visual Studio.
Let's create an MVC controller and name it as 'PersonController.cs' and add an action method as below.
PersonController.cs: us…

Blazor Server CRUD Operations

Introduction: Blazor Server is a web framework to develop server-side single-page applications. Blazor is made up of components with the combinations on C#, Html, CSS.  Blazor Server is production-ready from the .Net Core 3.0.  Blazor Server Working Mechanism:Blazor Server is a very light-weight web development framework. In Blazor Server, not all code gets downloaded to the client browsers. Blazor Server made of components these components can be a block of code or page with respective navigation. Blazor server application communicates with the server with a SignalR background connection which is inbuilt functionality. Application click,  form submission, change events, application page navigation every operation is carried out by the SignalR connection by communicating with the server. Blazor updates the Html DOM very gently on every data update without any overhead. Blazor Server application maintains a nice intelligent tree structure to update the required information or changed …

NestJS API CRUD Operations With MongoDB

Introduction: NestJS is a framework used to develop server-side applications. NestJS built on top of Node.js frameworks like Express. It is a combination of Progressive Javascript, Object-Oriented Programming, Functional Programming, and Functional Reactive Programming.
Nest CLI Installation: Using Nest CLI we are able to generate the NestJS starter project with the default template. To install Nest CLI globally over our system open command prompt and run the command
npm i -g @nestjs/cli Now create a sample project by using Nest CLI command  nest new your_project_name package.json: Now open the package.json file from the sample application created, you can observe few properties like "scripts", "dependencies", and "devDependencies".
"dependencies" contains all plugins to be installed and used them to run the application.
"devDependencies" contain all plugins to be installed and used them at the time of application development.

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server.
Main Response Caching Headers are like below
Cache-ControlPragmaVary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response.private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores.max-age - this directive represents a time to hold a response in the - this directive represents no storing of response and always fetch the fresh response from serverno-store…