Sanjit Kumar Singh
How to enable Session in ASP.NET Core?

How to enable Session in ASP.NET Core?

By Sanjit Kumar Singh in .NET Core on Nov 26 2019
  • Amol Gunjal
    Jul, 2020 11
  • Vishal Yelve
    Jul, 2022 8

    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.

    • 0
  • Lalji Dhameliya
    Apr, 2021 27

    The Microsoft.AspNetCore.Session package:

    • Is included implicitly by the framework.
    • Provides middleware for managing session state.

    To enable the session middleware, Startup must contain:

    1. Any of the IDistributedCache memory caches. The IDistributedCache implementation is used as a backing store for session. For more information, see Distributed caching in ASP.NET Core.
    2. A call to AddSession in ConfigureServices.
    3. A call to UseSession in Configure.
    1. public void ConfigureServices(IServiceCollection services)
    2. {
    3. services.AddDistributedMemoryCache();
    4. services.AddSession(options =>
    5. {
    6. options.IdleTimeout = TimeSpan.FromSeconds(10);
    7. options.Cookie.HttpOnly = true;
    8. options.Cookie.IsEssential = true;
    9. });
    10. //services.AddControllersWithViews();
    11. //services.AddRazorPages();
    12. }

    app.UseSession(); in Configure method of startup.cs class.

    this way you can enable session in asp.net core

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS