Use Session in ASP.NET Core Razor Pages

On the Visual Studio, create new ASP.NET Core Web Application project

Select Empty Template

Click Ok 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;

namespace LearnASPNETCoreRazorPagesWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSession();

            services.AddMvc();
        }

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

            app.UseSession();

            app.UseMvc();
        }
    }
}

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




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

Create new class named Product.cs as below:

namespace LearnASPNETCoreRazorPagesWithRealApps.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 LearnASPNETCoreRazorPagesWithRealApps.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 Pages. In this folder, create new Razor Page named Index as below:

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

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class IndexModel : PageModel
    {
        public void OnGet()
        {
            HttpContext.Session.SetInt32("age", 20);
            HttpContext.Session.SetString("username", "abc");

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

            var products = new List<Product>()
            {
                new Product
                {
                    Id = "p01",
                    Name = "name 1",
                    Price = 4.5
                },
                new Product
                {
                    Id = "p02",
                    Name = "name 2",
                    Price = 11
                },
                new Product
                {
                    Id = "p03",
                    Name = "name 3",
                    Price = 7
                }
            };
            SessionHelper.SetObjectAsJson(HttpContext.Session, "products", products);
        }
    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.IndexModel
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="~/style.css" rel="stylesheet" type="text/css" />
</head>
<body>

    <a asp-page="index2">Display Session Values</a>

</body>
</html>




In Pages folder, create new Razor Page named Index2 as below:

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

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class Index2Model : PageModel
    {
        public int? age { get; set; }

        public string username { get; set; }

        public Product product { get; set; }

        public List<Product> products { get; set; }

        public void OnGet()
        {
            age = HttpContext.Session.GetInt32("age");
            username = HttpContext.Session.GetString("username");
            product = SessionHelper.GetObjectFromJson<Product>(HttpContext.Session, "product");
            products = SessionHelper.GetObjectFromJson<List<Product>>(HttpContext.Session, "products");
        }
    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.Index2Model
@{
    Layout = null;
}

<!DOCTYPE html>

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

    Age: @Model.age
    <br />
    Username: @Model.username
    <br>

    <h3>Product Info</h3>
    <table border="1">
        <tr>
            <td>Id</td>
            <td>@Model.product.Id</td>
        </tr>
        <tr>
            <td>Name</td>
            <td>@Model.product.Name</td>
        </tr>
        <tr>
            <td>Price</td>
            <td>@Model.product.Price</td>
        </tr>
    </table>

    <h3>Product List</h3>
    <table border="1">
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Price</th>
        </tr>
        @foreach (var product in Model.products)
        {
            <tr>
                <td>@product.Id</td>
                <td>@product.Name</td>
                <td>@product.Price</td>
            </tr>
        }
    </table>

</body>
</html>




Open Index Razor Page with following url: http://localhost:1115

Click link to open Index2 Razor Page with following url: http://localhost:1115/Index2

Output