Session is a feature in ASP.NET Core that enables us to save/store user data.
Session stores data in a dictionary on the server, using SessionId as the key.
The SessionId is stored in the client's cookie. The SessionId cookie is sent via per request.SessionId cookie is specific to each browser and cannot be shared between different browsers.
SessionId cookie does not specify a timeout and will be deleted when the browser is closed The browser session ends.
On the server side, sessions are retained for a limited time. The default session timeout is Server is 20 minutes, but can be configured.
Microsoft.AspNetCore.Session package provides middleware for managing sessions in ASP.NET Core. To use sessions in our application, we need to add this package as a dependency of the project in the project.json file.
The next step is to configure the session in the Startup class.
We need to call the "AddSession" method in the ConfigureServices method of the startup class.
The "AddSession" method has an overloaded method that accepts various session parameters
Options, such as idle timeout, cookie name and cookie domain, etc.
If we don't pass session options, the system will take the default options.
public class Startup { public void Configure(IApplicationBuilder app){ app.UseSession(); app.UseMvc(); app.Run(context => { return context.Response.WriteAsync("Hello World!"); }); } public void ConfigureServices(IServiceCollection services){ services.AddMvc(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(60); }); } }
How to access the session
public class HomeController : Controller{ [Route("home/index")] public IActionResult Index(){ HttpContext.Session.SetString("product","laptop"); return View(); } [Route("home/GetSessionData")] public IActionResult GetSessionData(){ ViewBag.data = HttpContext.Session.GetString("product");; return View(); } }
The above is the detailed content of How to enable sessions in C# ASP.NET Core?. For more information, please follow other related articles on the PHP Chinese website!