PROWAREtech

articles » current » asp-net-core » enable-sessions

ASP.NET Core: Enable Server Sessions

Enable server sessions to securely store user information related to the session; written in C#.

These examples use .NET Core 3.1, .NET 6 and .NET 8.

Easily enable sessions to store data server-side instead of in the browser (client-side).

.NET 6 Example

To enable sessions, modify the Program.cs to follow this snippet of code.

var builder = WebApplication.CreateBuilder(args);

// ...

builder.Services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(5); }); // NOTE: sets the amount of time until the session expires

// ...

var app = builder.Build();

// ...

app.UseSession(); // NOTE: required

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<HomeController> _logger;

		public HomeController(ILogger<HomeController> 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 });
		}
	}
}

.NET Core 3.1 Example

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<HomeController> _logger;

		public HomeController(ILogger<HomeController> 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


PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT