Implement Sessions In ASP.NET 5(vNext) And MVC 6

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. 

sess

Great! Thus, now we can use Session in vNext. Right?
 
Well, not yet.

We need to update the startup.cs file, as shown below:
  1. public void ConfigureServices(IServiceCollection services) {  
  2.     // Adds a default in-memory implementation of IDistributedCache  
  3.     services.AddCaching();  
  4.     services.AddSession();  
  5.     //// This Method may contain other code as well  
  6. }  
  7. and in Configure method write below code: public void Configure(IApplicationBuilder app) {  
  8.     app.UseSession();  
  9.     //// This Method may contain other code as well  
  10. }  
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:
    1. public IActionResult Index() {  
    2.     ////Context.Session.SetString("First", "I am first!"); ////Before Beta 8  
    3.     HttpContext.Session.SetString("First""I am first!"); ////From Beta 8 onwards  
    4.     return View();  
    5. }  
    6. Get Session syntax: public IActionResult Index() {  
    7.     ////var myValue = Context.Session.GetString("First"); ////Before Beta 8  
    8.     var myValue = HttpContext.Session.GetString("First"); ////From Beta 8 onwards  
    9.     return View();  
    10. }  
  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:
    1. private readonly IHttpContextAccessor _httpContextAccessor;  
    2. public SessionUtility(IHttpContextAccessor httpContextAccessor) {  
    3.     _httpContextAccessor = httpContextAccessor;  
    4. }  
    5. Set Session syntax: public void SetSession(string key, string value) {  
    6.     HttpContextAccessor.HttpContext.Session.SetString(key, value);  
    7. }  
    8. Get Session syntax: public string GetSession(string key) {  
    9.     return HttpContextAccessor.HttpContext.Session.GetString(key);  
    10. }  
    11. So, whole SessionUtility would be as below: public class SessionUtility {  
    12.     private readonly IHttpContextAccessor HttpContextAccessor;  
    13.     public SessionUtility(IHttpContextAccessor httpContextAccessor) {  
    14.         HttpContextAccessor = httpContextAccessor;  
    15.     }  
    16.     public void SetSession(string key, string value) {  
    17.         HttpContextAccessor.HttpContext.Session.SetString(key, value);  
    18.     }  
    19.     public string GetSession(string key) {  
    20.         return HttpContextAccessor.HttpContext.Session.GetString(key);  
    21.     }  
    22. }  
    and it would be registered as:
    1. 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:
    1. public void Configure(IApplicationBuilder app) {  
    2.     app.UseSession();  
    3.     app.Map("/session", subApp => {  
    4.         subApp.Run(async context => {  
    5.             int visits = 0;  
    6.             visits = context.Session.GetInt32("visits") ? ? 0;  
    7.             context.Session.SetInt32("visits", ++visits);  
    8.             await context.Response.WriteAsync("Counting: You have visited our page this many times: " + visits);  
    9.         });  
    10.     });  
    11. }  

Remember!

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.

  1. "frameworks": {  
  2. "dnx451": { },  
  3. "dnxcore50": { } // <-- Remove this if it is in your project.json file.  
  4. },  
Reason?

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!