The Microsoft.AspNetCore.Session package provides middleware for managing session state.
- 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]
- 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]
- 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]
Reblogged this on Rijwan Ansari's Blog.
If you’re looking for regular updates on .net programming tech, you could keep a watch on websites like http://www.dotnetbasic.com