How to enable Session in C# ASP.NET Core?

CsharpServer Side ProgrammingProgramming

Session is a feature in ASP.NET Core that enables us to save/store the user data.

Session stores the data in the dictionary on the Server and SessionId is used as a key. The SessionId is stored on the client at cookie. The SessionId cookie is sent with every request.

The SessionId cookie is per browser and it cannot be shared between the browsers.

There is no timeout specified for SessionId cookie and they are deleted when the Browser session ends.

At the Server end, session is retained for a limited time. The default session timeout at the Server is 20 minutes but it is configurable.

Microsoft.AspNetCore.Session package provides middleware to manage the sessions in ASP.NET Core. To use session in our Application, we need to add this package as a dependency in project.json file.

The next step is to configure session in Startup class.

We need to call "AddSession" method in ConfigureServices method of startup class.

The "AddSession" method has one overload method, which accepts various session options such as Idle Timeout, Cookie Name and Cookie Domain etc.

If we do not pass the session options, the system will take the default options

Example

public class Startup {
   public void Configure(IApplicationBuilder app){
      app.UseSession();
      app.UseMvc();
      app.Run(context => {
         return context.Response.WriteAsync("Hello World!");
      });
   }
   public void ConfigureServices(IServiceCollection services){
      services.AddMvc();
      services.AddSession(options => {
         options.IdleTimeout = TimeSpan.FromMinutes(60);
      });
   }
}

How to access the session

public class HomeController : Controller{
   [Route("home/index")]
   public IActionResult Index(){
      HttpContext.Session.SetString("product","laptop");
      return View();
   }
   [Route("home/GetSessionData")]
   public IActionResult GetSessionData(){
      ViewBag.data = HttpContext.Session.GetString("product");;
      return View();
   }
}
raja
Published on 24-Sep-2020 13:14:30
Advertisements