In this article I will explain with an example, how to get and set Session object (variable) in ASP.Net Core Razor Pages.
Note: For enabling and configuring Session in ASP.Net Core Razor Pages, please refer my article ASP.Net Core Razor Pages: Enable Session.
You will need to import the following namespace.
using Microsoft.AspNetCore.Http;
Razor PageModel (Code-Behind)
The PageModel consists of two Handler methods.
Handler method for handling GET operation
Inside this Handler method, Session object is set.
The Session object is set using the SetString method of the HttpContext.Session property.
Handler method for handling Button Click and POST operation
When the Get Session Button is clicked, the following Handler method is executed.
Inside this Handler method, the Session variable name is received as parameter. Then the value of the Session object is fetched using GetString method of the HttpContext.Session property and assigned to ViewData object.
public class IndexModel : PageModel
    public void OnGet()
        //Set value in Session object.
        HttpContext.Session.SetString("Person", "Mudassar");
    public void OnPostSubmit(string sessionName)
        //Get value from Session object.
        ViewData["Message"] = HttpContext.Session.GetString(sessionName);
Razor Page (HTML)
The HTML of Razor Page consists of an HTML Form with a TextBox element and a Submit Button.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostSubmit but here it will be specified as Submit when calling from the Razor HTML Page.
When the Get Session Button is clicked, the Form gets submitted and the value of TextBox is sent to the PageModel.
Finally, the ViewData object named Message is checked for NULL and if it is not NULL then the value of Session object is displayed using JavaScript Alert Message Box.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Get_Set_Session_Core_Razor.Pages.IndexModel
    Layout = null;
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width" />
    <form method="post">
        <input type="text" id="txtSessionName" name="SessionName" />
        <input type="submit" value="Get Session" asp-page-handler="Submit" />
    @if (ViewData["Message"] != null)
        <script type="text/javascript">
            window.onload = function () {
ASP.Net Core Razor Pages: Get and Set Session object (variable)