To use session in asp.net core you need to follow following steps:
Step 1
- Install Microsoft.AspNetCore.Session package from Nuget.
- AddSession call in ConfigureServices.
- UseSession call in IApplicationBuilder.
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Adds a default in-memory implementation of IDistributedCache. services.AddDistributedMemoryCache(); services.AddSession(options => { // Set a short timeout for easy testing. options.IdleTimeout = TimeSpan.FromSeconds(10); options.Cookie.HttpOnly = true; }); }Step 2
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSession(); app.UseMvc(); //app.Run(async (context) => //{ // await context.Response.WriteAsync("Hello World!"); //}); }Step 3
public class IndexModel : PageModel { public void OnGet() { HttpContext.Session.SetString("NameKey", "Microsoft "); ViewData["Name"] = HttpContext.Session.GetString("NameKey"); } }