In this article I will explain with an example, how to display or access Session object inside view in ASP.Net Core MVC.
Note: For enabling and configuring Session in ASP.Net Core, please refer my article Enable Session in ASP.Net Core.
You will need to import the following namespace.
using Microsoft.AspNetCore.Http;
The Controller consists of the following two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for displaying the Session object
When the Display Session Button is clicked, SetSession Action method is executed which saves the value to the Session using the SetString method.
Finally, the Action is redirected to the Index Action method.
public class HomeController : Controller
    public IActionResult Index()
        return View();
    public IActionResult SetSession()
        //Set value in Session object.
        HttpContext.Session.SetString("Name", "Mudassar Khan");
        return RedirectToAction("Index");
Inside the View, the IHttpContextAccessor Interface object is injected in order to access the Session and its functions inside the View.
Note: For configuring IHttpContextAccessor in ASP.Net Core, please refer my article Using HttpContext in ASP.Net Core.
The View consists of an HTML Form with following ASP.Net Tag Helpers attributes.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of a Submit Buttons i.e. for Displaying Session.
The Submit Button has been set with a FormAction attribute which specifies the Action method which will be called when the Submit Button is clicked.
When the Display Session button is clicked, the value from the Session object is displayed using the GetString method.
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor Accessor
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
    Layout = null;
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width"/>
    <form method="post" asp-controller="Home">
        <input type="submit" id="btnSet" formaction="@Url.Action("SetSession")" value="Display Session"/>
        Session: @Accessor.HttpContext.Session.GetString("Name")
ASP.Net Core MVC: Display (Access) Session object inside View