ASP.NET Core 6.0 MVC Tutorial Day 7 (Session Management)

ASP.NET Core 6.0 MVC Tutorial Day 7

Learning Objective: Let’s do session management using asp.net core 6.0. Example of storing values to session, example of getting value from session.

Step 1

Create ASP.NET Core 6.0 Project and now its time to update Program.cs file.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddDistributedMemoryCache();

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromSeconds(1800);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseSession();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Now update Home controller code.

using Microsoft.AspNetCore.Mvc;
using SessionManagement.Models;
using System.Diagnostics;

namespace SessionManagement.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

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

        public IActionResult Index()
        {
            return View();
        }
        public IActionResult SetSession()
        {
            return View();
        }
        public IActionResult SetSession2(String fname, String lname)
        {
            HttpContext.Session.SetString("fname", fname);
            HttpContext.Session.SetString("lname", lname);

            return RedirectToAction("GetSession");
            // return View();
        }
        public IActionResult GetSession()
        {
            var fname = HttpContext.Session.GetString("fname");
            var lname = HttpContext.Session.GetString("lname");
            
            ViewData["fname"] = fname;
            ViewData["lname"] = lname;

            return View();
        }
        public IActionResult Privacy()
        {
            return View();
        }

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

Now It’s time to update View

SetSession

@{
    ViewData["Title"] = "Set Session";
}

<div class="text-center">
    <h1 class="display-4">Set Session</h1>
    

    <form method="post" action="SetSession2">
        <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
        <input type="text" id="lname" name="lname" value="Doe"><br>
  <input type="submit" value="Submit" />
</form>

</div>

GetSession

@{
    ViewData["Title"] = "Set Session";
}

<div class="text-center"> 
    <h1 class="display-4">Get Value from Session</h1>


    <h2> First Name is : @ViewData["fname"] </h2>
    <h2> Last Name is : @ViewData["lname"] </h2>

</div>

Download Complete Code