Using Session in ASP.Net Core MVC Application

In this tutorial, we are going to see how to configure an ASP.Net Core MVC Application to use Session state. In previous versions of ASP.Net, session management is straight forward by using HttpSessionState. But in ASP.Net Core MVC application it is not straight forward, we have to add and configure ISession Service along with an IDistributedCache implementation. In ASP.Net Core, ISession exposes new API to support saving and retrieving objects from Session state.

NOTE: Updated this tutorial on 2/26/2017 with MSBuild based Dotnet SDK.

Create an ASP.Net Core Application using VS 2017. I am using following version of Dotnet SDK which is based on MSBuild/CSProj (remember that previous versions of ASP.Net Core are based on Project.json/XProj.).

image

To get Session state available in application, we need add following reference to following dependency (remember that everything in ASP.Net Core is service based, we have to add packages explicitly).

<ItemGroup>
  <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
  <PackageReference Include="Microsoft.AspNetCore" Version="1.0.3" />
  <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.0.2" />
  <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.0" />
  <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.0.1" />
  <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.0" />
  <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.0.1" />
  <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.0.1" />
</ItemGroup>

Now add ISession and IDistributedCache services to IServiceCollection in ConfigureServices method of Startup class. ISession needs IDistributedCache to store and retrieve items to a persistent medium. AddDistributedMemoryCache is used to store items in memory of the server. As Session uses cookie to tie up values back at the server, we can configure cookie name, idle timeout, domain, path and HttpOnly properties as shown below.

services.AddDistributedMemoryCache();
services.AddSession(options =>
{
    options.CookieHttpOnly = true;
    options.CookieName = ".ASPNetCoreSession";
    options.IdleTimeout = TimeSpan.FromMinutes(10);
    options.CookiePath = "/";
});

As the last step of configuration, lets add Session service to our HTTP Pipeline as shown below in Configure method of Startup class. One important point to be remembered is that UseSession() should be added to pipeline before UseMvc().

app.UseSession();

Now lets create a type which will be stored in Session. I created below class for demonstration.

public class UserContent
{
    public string Username { get; set; }
    public string Email { get; set; }
    public List<string> Roles { get; set; }
}

In ASP.Net Core Application, saving and retrieving complex objects is not straight forward (ISession API supports Int32 and String types through SetInt32, SetString, GetInt32 and GetString). We have to serialize the object and save it, when retrieving the object we have to deserialize it. We will be using JSON serialization (using Newtonsoft nuget) which is light and easy to use. Following helper class is helpful in performing afore said functionality.

public static class SessionExtensions
{
    public static void SetSession(this ISession session, string key, object value)
    {
        session.SetString(key, JsonConvert.SerializeObject(value));
    }

    public static T GetSession<T>(this ISession session, string key)
    {
        return JsonConvert.DeserializeObject<T>(session.GetString(key));
    }
}

Now create below actions to demonstrate Session usage with the help of above extension methods. In Index action, we are setting the session and in About action we are retrieving the session.

public IActionResult Index()
{
    HttpContext.Session.SetSession("UserDetails", new UserContent
    {
        Username = "Intstrings",
        Email = "intstrings@gmail.com",
        Roles = new List<string> { "Admin" }
    });
    return Json(true);
}

public IActionResult About()
{
    var userContent = HttpContext.Session.GetSession<UserContent>("UserDetails");
    return Json(userContent);
}

Now using Postman tool, lets make a request to Index action. We should see below response.

image

Lets make a request to About Action. We should see below response with UserContext data which has been loaded from session and sent back in JSON format.

image

That’s it for now. Happy Coding and Stay Tuned!!!

You may also like...