Skip to content

Session in Asp.Net MVC Core 1.0

You all have used session in classic Asp.Net and that is pretty easy to use. But if you are going to use session in new Asp.Net core, then you have to use it in different way.

In asp.net core things are pluggable, like middleware, like in Django. So you need to add it in your project.json file. You can download it from NuGet. You can add following packages in your package.json file:

"Microsoft.AspNetCore.Session": "1.0.0",
"Microsoft.Extensions.Caching.Memory": "1.0.0"

Add these lines in the ConfigureServices method of Statup.cs class:

services.AddDistributedMemoryCache();
services.AddSession();

And this line in the Configure method of startup.cs but before the app.UseMVC line.

app.UseSession();

Now in your controller you need to include Microsoft.AspNetCore.Http reference.

using Microsoft.AspNet.Http;

For adding data in session you can do it following way:

HttpContext.Session.SetString("Username", "Mike");
HttpContext.Session.SetInt32("UserID", 1);
HttpContext.Session.SetBoolean("IsAdmin", true);

And here’s how you can retrieve those values:

ViewBag.Username = HttpContext.Session.GetString("Username");
ViewBag.UserID = HttpContext.Session.GetInt32("UserID");

In some case you need to check session in View directly. In that case you have to add following reference in your view:

@using Microsoft.AspNetCore.Http

And you can check session in following way directly:

@if (Context.Session.GetInt32("UserID") != null)
 {
     //Do something
 }

Thanks.

Be First to Comment

Leave a Reply

Your email address will not be published.