Enable and Use ASP.NET Core Sessions

This example uses ASP.NET Core 3.1.

To enable sessions, modify Startup.cs as follows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace EnableSessions
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {


            // ################ THIS IS NEWLY ADDED ################
            services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(5); });


            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();


            app.UseSession(); // ################ THIS IS NEWLY ADDED ################


            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Then to use sessions, modify the HomeController.cs file as follows.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using EnableSessions.Models;
using Microsoft.AspNetCore.Http; //######## THIS LINE NEWLY ADDED ########

namespace EnableSessions.Controllers
{
	public class HomeController : Controller
	{
		private readonly ILogger _logger;

		public HomeController(ILogger logger)
		{
			_logger = logger;
		}

		public IActionResult Index()
		{
			//############ THE THREE FOLLOWING LINES ARE NEWLY ADDED ############
			HttpContext.Session.SetString("username", "John");
			HttpContext.Session.SetInt32("attempts", 3);
			HttpContext.Session.CommitAsync();


			return View();
		}

		public IActionResult Privacy()
		{
			//############ THE TWO FOLLOWING LINES ARE NEWLY ADDED ############
			var username = HttpContext.Session.GetString("username");
			var attempts = HttpContext.Session.GetInt32("attempts");

			return View();
		}

		[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
		public IActionResult Error()
		{
			return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
		}
	}
}

Coding Video

https://youtu.be/R2Jh8HxpMuU