In this Tutorial, we will learn How to Use Session State in ASP.Net Core. Session state in ASP.Net Core enables you to store user data and persist the data across requests from the same client.
Install Required Software
Create ASP.NET Core Web Application Project
- Open Visual Studio and Create a new project.
- Select ASP.NET Core Web Application and give it a name.
- Choose the template and select Create
Install NuGet Packages
Install-Package Microsoft.AspNetCore.Session
Session in ASP.NET Core
How to Enable Session in ASP.Net Core
We need to add the session middleware component to the ASP.Net Core pipeline. To enable a session in ASP.Net Core you must add any of the IDistributedCache memory caches you want to use as backing storage for the session
Also, check the previous article How to execute stored procedure in ASP.NET Core Web API | Entity Framework core
builder.Services.AddDistributedMemoryCache(); builder.Services.AddSession(options => { options.IdleTimeout= TimeSpan.FromSeconds(5); options.Cookie.HttpOnly= true; options.Cookie.IsEssential= true; }); builder.Services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2);
Configure the HTTP Request Pipeline
We need to add app.Usesession() in program.cs class.
app.UseSession();
Complete Program.cs Class
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddDistributedMemoryCache(); builder.Services.AddSession(options => { options.IdleTimeout= TimeSpan.FromSeconds(5); options.Cookie.HttpOnly= true; options.Cookie.IsEssential= true; }); builder.Services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSession(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
Create Controller
using Microsoft.AspNetCore.Mvc; using Session_AspNet_Tutorial.Models; using System.Diagnostics; namespace Session_AspNet_Tutorial.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { HttpContext.Session.SetString("Message", "Hello World"); HttpContext.Session.SetInt32("EmployeeCode", 101); return View(); } public IActionResult Privacy() { ViewBag.Message = HttpContext.Session.GetString("Message"); ViewBag.Employee = HttpContext.Session.GetInt32("EmployeeCode"); return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }