The Microsoft.AspNetCore.Session package provides middleware for managing session state.

  1. Add the following heightened line in your Startup.cs

[code language=”csharp”]

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Adds a default in-memory implementation of IDistributedCache
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a time for session
options.IdleTimeout = TimeSpan.FromSeconds(200);
options.Cookie.HttpOnly = true;
});
}

public void Configure(IApplicationBuilder app)
{
app.UseSession();
app.UseMvcWithDefaultRoute();
}
[/code]

  1. Following line of code is needed to set the session value.

[code language=”csharp”]

public class HomeController : Controller
{
const string SessionStoreName = “_StoreName”;
const string SessionStoreID = “_StoreID”;

public IActionResult Index()
{
// Requires using Microsoft.AspNetCore.Http
HttpContext.Session.SetInt32(SessionStoreID, 3);
HttpContext.Session.SetString(SessionStoreName, “ABC Store”);
return RedirectToAction(“SessionStore”);
}
[/code]

  1. To get the session value

[code language=”csharp”]

public IActionResult SessionStore ()
{
var storename = HttpContext.Session.GetString(SessionStoreName);
var storeID = HttpContext.Session.GetInt32(SessionStoreID);
return Content($”Store Name: “{ storename }”,Store ID: “{ storeID}””);
}
[/code]

2 thoughts on “How to set and get the session value in asp.net core.”

Leave a Reply

Your email address will not be published. Required fields are marked *