Session in Asp.net Core

HTTP is a stateless protocol. Therefore, when we request any page, every HTTP request is treated separately as an individual request.

Here we learn how to use Session in Asp.net Core web application. If you have some experience in developing web application using earlier asp.net framework or any other language, then you probably already familiar with session, and the functionality of session remain same, but implementation differ from framework to framework, even asp.net core session implementation is little different than earlier asp.net framework.

var studentName = Session["stuName"];

Session is a mechanism of storing user data in a dictionary object using key-value combination, and accessing data from different page for a specific duration.

services.AddSession(options => {
        options.Cookie.Name = ".WebTrainingRoom.Session";
        options.IdleTimeout = TimeSpan.FromMinutes(1);
        options.Cookie.IsEssential = true;
               
    });

There are two Session state in asp.net core, In-Proc (In-memory) and Out-Proc (Distributed session). Here in this tutorial we talk about In-memory session management.

How to use session in Asp.net Core

If you have experience in working with earlier asp.net version, you must have worked with session object, but in asp.net core implementation of session object is little different than earlier version, in earlier asp.net we could straight away store and retrieve any type of information from session just by using key-value

But in asp.net core you have to do some additional work to use session object in application, you have to add session in middleware pipeline

Like earlier Asp.Net framework, session object is not available by default, you need to install and register in http pipeline.

To use session in Asp.net Core Application you need to install Microsoft.AspNetCore.Session package from NuGet Package Manager.

install Microsoft.AspNetCore.Session

Step 1
Open startup.cs file and inside ConfigureServices method register the AddSession() method, and add UseSession method to IApplicationBuilder instance in Configure method.

public void ConfigureServices(IServiceCollection services)
{            
    services.AddSession();
}

Alternatively, you also can set the optional parameter session time out value at the time of registering session object in middleware pipeline.

services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(1);   
    });

"IdleTimeout" is actually indicates session timeout, it says after that specified time duration, the session will get expired, if there is not activity from that user session.

We also can set session cookie name, by default the cookie name is .AspNetCore.Session.

services.AddSession(options => {
        options.Cookie.Name = ".WebTrainingRoom.Session";
        options.IdleTimeout = TimeSpan.FromMinutes(1);
        options.Cookie.IsEssential = true;
               
    });

Step 2
Now in Configure method call UseSession() method

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSession();
}

Step 3
Now install Microsoft.AspNetCore.Session utility from Nugget

Set and retrieve value from Session object in Asp.net Core

In ASP.NET Core Session object there are 3 methods to set the session value, which are Set, SetInt32 and SetString.

HttpContext.Session.SetString("sessionKeyString", "WebTrainingRoom");
HttpContext.Session.SetInt32("sessionKeyInt", 10);

And three methods for retrieving values from session , which are Get, GetInt32 and GetString

string _sessionStringvalue = HttpContext.Session.GetString("sessionKeyString");
int? _sessionIntValue = HttpContext.Session.GetInt32("sessionKeyInt");

So far we have seen how to use session object to store simple information, but there is no straight way to store complex object in asp.net core session.
Now we learn how to store complex object in session

Asp net core session complex objects example

Let’s see how to store complex object in Asp.net core session!

So we have already understood there is no straight way of storing complex data in session like we used to do in earlier asp.net version

But, there is way to store complex object in session, we can convert complex object into Json String, then store them in session object using the same SetString function, here is an working example of how we can store complex data in asp.net core session.

We have to create an additional class (with Session extension methods) to add any object current Session, look at the example bwlow.

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
public static class SessionHelper
{
    public static void SetObjectInSession(this ISession session, string key, object value)
    {
        session.SetString(key, JsonConvert.SerializeObject(value));
    }

    public static T GetCustomObjectFromSession<T>(this ISession session, string key)
    {
        var value = session.GetString(key);
        return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
    }
} 

Now let's call the above methods to add and retrieve complex object in session.
In following example we add a student object list in session and retrieve from session

AdminUser _user = new AdminUser();
_user.UserName = Username;
_user.Password = Password;

// set in session
HttpContext.Session.SetObjectInSession("adminUser", _user);


// get from session
AdminUser _adminuser= HttpContext.Session.GetCustomObjectFromSession<AdminUser>("adminUser");
Session handling in Controller

Once user hit the login button on web page data gets submitted to action result IActionResult index(UserModel model).

If authenticated successfully, then user object gets stored in session and UI gets redirected to controlpanel.

In control panel we check the session, if user object found we display user information on view, otherwise throw out user to login page or unauthorised page.

public class userController : Controller
{
    IAuthService _authService;
    public userController(IAuthService authservice)
    {
        _authService = authservice;
    }

    [HttpPost]
    public IActionResult index(UserModel model)
    {
        User u= _authService.GetUser(model.Username, model.Password);
        if (u != null)
        {
            SessionHelper.SetObjectAsJson(HttpContext.Session, "userObject", u);
            return RedirectToAction("controlpanel");
        }
        return View(model);
    }


    public IActionResult controlpanel()
    {
	    User user = SessionHelper.GetObjectFromJson<User>(HttpContext.Session, "userObject");
	    if (user == null)
	    { 
		    //throw out;
	    }
	    // do whatever you want with user object.

	    ViewBag.CurrentUser = user;
	    return View();
    }
}
Remove Session Key

Now you come across situation when you want to remove some session key explicitly from current session, as we have seen in above example that we can add any number of keys in session object, so here we see how to remove any key from session object.

public IActionResult Logout()
{
    HttpContext.Session.Remove("userObject");
    return View();
}

We also can remove all keys from session, which is essential for successful sign-out.

public IActionResult Logout()
{
    HttpContext.Session.Clear();
    HttpContext.SignOutAsync();
    return View();
}

Hope you understood how to work with session in asp.net core and storing complex object in session asp.net core.

Asp.Net Core C# Examples | Join Asp.Net MVC Course