Use Session in ASP.NET Core MVC 5

On the Visual Studio, select Create a new project from Get Started

Select ASP.NET Core Web Application




Input Project Name and select Location for new project

Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create button to finish




Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCoreMVC5
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            services.AddSession();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSession();

            app.UseStaticFiles();

            app.UseRouting();

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

        }
    }
}

Create new folder named Models. In Models folder, create new entities class as below:

Create new class named Product.cs as below:

namespace LearnASPNETCoreMVC5.Models
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }
}




Create new folder named Helpers. In this folder, create new helper named SessionHelper.cs as below:

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace LearnASPNETCoreMVC5.Helpers
{
    public static class SessionHelper
    {
        public static void SetObjectAsJson(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T GetObjectFromJson<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }
    }
}

Create new folder named Controllers. In this folder, create new controller named DemoController.cs as below:

using LearnASPNETCoreMVC5.Helpers;
using LearnASPNETCoreMVC5.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace LearnASPNETCoreMVC5.Controllers
{
    [Route("demo")]
    public class DemoController : Controller
    {
        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
            HttpContext.Session.SetInt32("age", 20);

            HttpContext.Session.SetString("username", "abc");

            Product product = new Product
            {
                Id = "p01",
                Name = "Name 1",
                Price = 5
            };
            SessionHelper.SetObjectAsJson(HttpContext.Session, "product", product);

            List<Product> products = new List<Product>() {
                new Product {
                    Id = "p01",
                    Name = "Name 1",
                    Price = 5
                },
                new Product {
                    Id = "p02",
                    Name = "Name 2",
                    Price = 9
                },
                new Product {
                    Id = "p03",
                    Name = "Name 3",
                    Price = 2
                }
            };
            SessionHelper.SetObjectAsJson(HttpContext.Session, "products", products);
            return View("Index");
        }

    }
}




Create new folder named Views. In this folder, create new folder named Demo and add new views as below:

In Demo folder, create new view named Index.cshtml as below:

@using Microsoft.AspNetCore.Http;
@using LearnASPNETCoreMVC5.Helpers;
@using LearnASPNETCoreMVC5.Models;

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <h3>Session Page</h3>
    Age: @Context.Session.GetInt32("age")
    <br />
    Username: @Context.Session.GetString("username")

    <h3>Product Info</h3>
    @{
        Product product = SessionHelper.GetObjectFromJson<Product>(Context.Session, "product");
    }
    Id: @product.Id
    <br />
    Name: @product.Name
    <br />
    Price: @product.Price

    <h3>Product List</h3>
    @{
        List<Product> products = SessionHelper.GetObjectFromJson<List<Product>>(Context.Session, "products");
    }
    @foreach (var p in products)
    {
        <div>
            Id: @p.Id
            <br />
            Name: @p.Name
            <br />
            Price: @p.Price
            <br />
            ==================
            <br />
        </div>
    }

</body>
</html>




Select Views folder and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish

In _ViewImports.cshtml file and TagHelpers library as below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers




Access Index action in Demo controller with following url: http://localhost:48982

Output