How to enable Session in ASP.NET Core?
How to enable Session in ASP.NET Core?
1)First, add dependency in project.json - "Microsoft.AspNetCore.Session", 2)In startup.cs and add AddSession() and AddDistributedMemoryCache() lines to the ConfigureServices like this- services.AddDistributedMemoryCache(); //This way ASP.NET Core will use a Memory Cache to store session variables services.AddSession(options => { options.IdleTimeout = TimeSpan.FromDays(1); // It depends on user requirements. options.CookieName = ".My.Session"; // Give a cookie name for session which will be visible in request payloads. }); 3)Add the UseSession() call in Configure method of startup like this- app.UseSession(); //make sure add this line before UseMvc() 4)In Controller, Session object can be used like this- using Microsoft.AspNetCore.Http; public class HomeController : Controller { public IActionResult Index() { HttpContext.Session.SetString("SessionVariable1", "Testing123"); return View(); } public IActionResult About() { ViewBag.Message = HttpContext.Session.GetString("SessionVariable1"); return View(); } } If you are using cors policy then sometimes it may give errors, after enabling session regarding headers about enabling AllowCredentials header and using WithOrigins header instead of AllowAllOrigins.
The Microsoft.AspNetCore.Session package:
To enable the session middleware, Startup must contain:
public void ConfigureServices(IServiceCollection services){services.AddDistributedMemoryCache();services.AddSession(options =>{options.IdleTimeout = TimeSpan.FromSeconds(10);options.Cookie.HttpOnly = true;options.Cookie.IsEssential = true;});//services.AddControllersWithViews();//services.AddRazorPages();}
app.UseSession(); in Configure method of startup.cs class.
this way you can enable session in asp.net core
have a look into below URL
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1