Imagine you have created an MVC project and you are all set to create a session object in order to save your current user Email but after few minutes, you realize that the session object is not working, as it was before.

Oh! Why is it so?

It is because .NET team has created a NuGet package for Session, which is nothing but a very fresh ASP.NET 5 Session State middleware.

OK. So, how to get it?

To install Microsoft.AspNet.Session, run the command, given below, in the Package Manager Console. 

We need to update the startup.cs file, as shown below:

public void ConfigureServices(IServiceCollection services) {  
    // Adds a default in-memory implementation of IDistributedCache  
    services.AddCaching();  
    services.AddSession();  
    //// This Method may contain other code as well  
}  
and in Configure method write below code: public void Configure(IApplicationBuilder app) {  
    app.UseSession();  
    //// This Method may contain other code as well  
}  

How to get and set session?

Let's take some examples.

1. Suppose, you want to use Session in your controller class. For it, you simply have to write Context.Session to access Session.

Set Session syntax:

public IActionResult Index() {  
    ////Context.Session.SetString("First", "I am first!"); ////Before Beta 8  
    HttpContext.Session.SetString("First""I am first!"); ////From Beta 8 onwards  
    return View();  
}  
Get Session syntax: public IActionResult Index() {  
    ////var myValue = Context.Session.GetString("First"); ////Before Beta 8  
    var myValue = HttpContext.Session.GetString("First"); ////From Beta 8 onwards  
    return View();  
}  

2. Suppose, you want to use Session in a normal class. If you’re not in a Controller, you can still access the HttpContext by injecting IHttpContextAccessor, as shown below:

private readonly IHttpContextAccessor _httpContextAccessor;  
public SessionUtility(IHttpContextAccessor httpContextAccessor) {  
    _httpContextAccessor = httpContextAccessor;  
}  
Set Session syntax: public void SetSession(string key, string value) {  
    HttpContextAccessor.HttpContext.Session.SetString(key, value);  
}  
Get Session syntax: public string GetSession(string key) {  
    return HttpContextAccessor.HttpContext.Session.GetString(key);  
}  
So, whole SessionUtility would be as below: public class SessionUtility {  
    private readonly IHttpContextAccessor HttpContextAccessor;  
    public SessionUtility(IHttpContextAccessor httpContextAccessor) {  
        HttpContextAccessor = httpContextAccessor;  
    }  
    public void SetSession(string key, string value) {  
        HttpContextAccessor.HttpContext.Session.SetString(key, value);  
    }  
    public string GetSession(string key) {  
        return HttpContextAccessor.HttpContext.Session.GetString(key);  
    }  
}  

and it would be registered as:

services.AddTransient<SessionUtility>();  

Here, SessionUtility should be registered only as Transient or Scoped and not Singleton as HttpContext is per-request based.

Please note, I have used it with the key value pair of the string, but you can create the same SessionUtility for the complex scenarios.

Now, suppose you want to check how many times a visitor has visited your site.

For it, you need to add the code, given below, in your startup.cs:

public void Configure(IApplicationBuilder app) {  
    app.UseSession();  
    app.Map("/session", subApp => {  
        subApp.Run(async context => {  
            int visits = 0;  
            visits = context.Session.GetInt32("visits") ? ? 0;  
            context.Session.SetInt32("visits", ++visits);  
            await context.Response.WriteAsync("Counting: You have visited our page this many times: " + visits);  
        });  
    });  
}  

Important!

If you have followed the steps, given above and you still can't get success, you might need a look in your project.json file for the following piece of the code. Well, it should be there.

"frameworks": {  
"dnx451": { },  
"dnxcore50": { } // <-- Remove this if it is in your project.json file.  
},  

Why?

ASP.NET5 Sessions aren’t supported by the DNX Core Runtime.

NuGet package site: https://www.nuget.org/packages/Microsoft.AspNet.Session/

Session is still in its beta versions. Thus, some changes might come, which I will update in this post.

Stay tuned for more updates!