Skip to main content

.NET Core: All About Sessions In ASP.NET Core

We'll quickly discuss how we used to use Sessions before ASP.NET Core and then we'll see how to access Sessions in ASP.NET Core.

Session In Pre-ASP.NET Core era
  • You get Session functionality by default (without adding any package)
  • Previously, you would have accessed Session by -
    • Session variable in your Controllers/Forms
    • System.Web.HttpContext.Current.Session in places where you don't have direct access to the Session variable.
  • Anything you store in session is stored as Object. You store values in Key/Value format.
Session["mydata"] = 10;   
Or to access on those places where Session is not available (e.g. Non-Controller classes)
System.Web.HttpContext.Current.Session["mydata"] = 10;   
  • Quite difficult to mock Session Object for Unit Testing 
Session in ASP.NET Core 2.2
  1. Now, Session is not available by default.
  2. You need to add the following package. Meta package by default provides you this.
<PackageReference Include="Microsoft.AspNetCore.Session" Version="2.2.0" />  
  1. In Startup.ConfigureServices, you need to add the following to register services with DI Container.
services.AddDistributedMemoryCache();//To Store session in Memory, This is default implementation of IDistributedCache    
services.AddSession();  
  1. In Startup.Configure, you need to add the following (before UseMVC) to add Session Middleware.
app.UseCookiePolicy();      
app.UseSession();      
app.UseMvc(routes => 
  1. Make sure the following is also there (It is added by default when you use ASP.NET Core MVC Template).
app.UseCookiePolicy();
  1. ASP.NET Core 2.2 onwards adds Cookie Consent (true) in the Startup file. When an application runs, the user needs to accept Cookie Consent on screen. When the user accepts the policy on the page, it creates a consent cookie. It is to follow GDPR and to give control to the user if the user wants to store cookies from a site or not. If the user doesn't accept that, Session does not work because Session requires a cookie to send/receive session Id. You may face this issue while working with ASP.NET Core MVC default template. 
How to access Session in Controller?
You will notice that you don't have "Session" variable available now. Controller now has a property "HttpContext" which has "Session" variable. So, you can access session in controller by using the following code.

var a = this.HttpContext.Session.GetString("login");    
HttpContext.Session.SetString("login", dto.Login);  

How to access Session in Non-Controller class?
Now, you don't have System.Web.HttpContext.Current.Session in ASP.NET Core. To access session in non-controller class –

  • First, register the following service in Startup.ConfigureServices;
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();  
  • Now, register a class (example - TestManager) where you want to access the Session in Startup.ConfigureServices;
services.AddScoped<TestManager>();  
Note
You may use AddTransient or AddSingleton according to your logic.
  • Now, in TestManager class, add the following code.
private readonly IHttpContextAccessor _httpContextAccessor;    
private readonly ISession _session;    
public TestManager(IHttpContextAccessor httpContextAccessor)    
{    
        _httpContextAccessor = httpContextAccessor;    
        _session = _httpContextAccessor.HttpContext.Session;    
}  
The above code is receiving IHttpContextAccessor object through dependency injection and then, it is storing Sessions in a local variable. 

How to access Session in View file?
Add the following at the top of your View file.

@using Microsoft.AspNetCore.Http    
@inject IHttpContextAccessor httpContextAccessor   

Then, you may access the Session variable in your View like following.

@httpContextAccessor.HttpContext.Session.GetString("login")   

What else is changed regarding Session? 
  • Session is non-locking now.
  • A session is not created until you have at least one value in it
  • You need to use functions to get & set data. Array syntax is not supported now.
  • Now, ISession only provides Get & Set method which takes & returns data in Byte Array format.
  • If you want to store data in the String format, you may add the following in your file and use extension methods.
using Microsoft.AspNetCore.Http;   

It exposes the new extension methods. 
SetInt32    
GetInt32    
SetString    
GetString    

Under the hood, these covert the data into bytes.

  • You may also write your own extension methods. For example, the following Extension Methods help you store & retrieve any complex type. 
public static class SessionExtensions        
{        
        public static void Set<T>(this ISession session, string key, T value)        
        {        
            session.Set<(key, JsonConvert.SerializeObject(value));        
        }        
        
        public static T GetObject<T>(this ISession session, string key)        
        {        
            var value = session.GetString(key);        
            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);        
        }        
}    
Summary
Session concepts are similar to what we've seen in earlier .NET Frameworks. The real difference is that now, it is cleaner & more flexible to use.

Reference: csharpccorner.com

Comments

Popular posts from this blog

.NET Core: Session Wrapper Design Pattern For ASP.NET Core

Here, we'll learn about Session Wrapper design pattern to ease the access of Session. We'll make our access of session "Typed". Also, we may apply any validation or constraint in this wrapper class. Step 1 - Create a Session Manager class   In this example, we are going to store two items in Session (i.e. ID & LoginName). We are injecting IHttpContextAccessor so that we can access the Session variable.  We are creating properties which are actually accessing Session variable and returning the data or writing the data to Session. We have added one helping property "IsLoggedIn" which is using other properties to make a decision. We may have more such helping/wrapper properties. using Microsoft.AspNetCore.Http; public class SessionManager       {           private readonly ISession _session;           private const String ID_KEY = "_ID";           private const String LOGIN_KEY = "_LoginName";           publ

Facade Design Pattern

Facade Intent Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. Motivation Structuring a system into subsystems helps reduce complexity. A common design goal is to minimize the communication and dependencies between subsystems. One way to achieve this goal is to introduce a  facade  object that provides a single, simplified interface to the more general facilities of a subsystem. Consider for example a programming environment that gives applications access to its compiler subsystem. This subsystem contains classes such as Scanner, Parser, ProgramNode, BytecodeStream, and ProgramNodeBuilder that implement the compiler. Some specialized applications might need to access these classes directly. But most clients of a compiler generally don't care about details like parsing and code generation; they merely want to compile some code. For them, the powerful but low-level

Tabla - An Indian classical instrument for Rythm

Tabla Indian music has fascinated the West for many years. The tabla in particular has attracted the attention of a number of American and European percussionists. It has been used in popular music as early as the 60's and is heard in the popular media even today. However, many percussionists shy away from this instrument. The reasons for not "getting into it" are varied. Sometimes it is the lack of instruments; sometimes lack of teachers; sometimes it is the belief that tabla is just too difficult. These are legitimate concerns but they are not insurmountable obstacles. This article will address the concerns of a musician just wishing to get started in tabla. We will discuss the theory of Indian music, how to purchase tabla, the basic technique, and compositional theory. All of this information should make the job of getting started much easier. We should first familiarize ourselves with the extensive theory of Indian music. Indian music is one of the oldest musical trad

How to make a Method Thread Safe?

In multi-threaded applications where multiple threads make calls to the methods of a single object, it is necessary that those calls be synchronized. If code is not synchronized, then one thread might interrupt another thread and the object could be left in an invalid state. A class whose members are protected from such interruptions is called thread-safe. Although, there is no rule that makes the code thread safe, the only thing you can do is make sure that your code will work no matter how many times is it being actively executed, each thread can be interrupted at any point, with each thread being in its own state/location , and this for each function (static or otherwise) that is accessing common objects. If a method (instance or static) only references variables scoped within that method then it is thread safe because each thread has its own stack: In this instance, multiple threads could call ThreadSafeMethod concurrently without issue. public class Thing { publ

Create VHD using DISKPART

Create Virtual Harddisk Using DISKPART Open the   Elevated Command Prompt   with Administrator Privileges and type the following commands: DISKPART CREATE VDISK FILE="c:\win7\win7.vhd" MAXIMUM=20000 SELECT VDISK FILE="c:\win7\win7.vhd" ATTACH VDISK CREATE PARTITION PRIMARY ASSIGN LETTER=X FORMAT QUICK LABEL=Windows7 EXIT This will create the  VHD  file of primary partition. You will see the newly attached disk in Disk Management with Drive Letter X: Attaching and Detaching VHD in  Windows 7 Right Click  on My Computer and Click ' Manage ' that will open up  Computer Management , in that click on  Disk Management . Just like previous part. Then Right Click on Disk Management and select  'Attach VHD'.  This will open new windows  'Attach Virtual Hard Disk ' Click on  OK  and that will attach the existing Virtual Hard Disk. Now, if you don't want to make write anything on the VHD, we