Saturday, 16 September 2017

How to use session in asp.net core 2.0? [Demo]

To use session in asp.net core you need to follow following steps:

  • Install Microsoft.AspNetCore.Session package from Nuget.
  • AddSession call in ConfigureServices.
  • UseSession call in IApplicationBuilder.

Step 1
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");
       
       }
   }

Watch Video how to use session in asp.net core 2.0?