In this article I will explain with an example, how to use Session in ASP.Net Core (.Net Core 7).
Note: For enabling and configuring Session in ASP.Net Core (.Net Core 7), please refer my article .Net Core 7: Enable Session in ASP.Net Core.
 
 

Controller

The Controller consists of the following Action method.

Action method for handling GET operation

Inside this Action method, Session object is set.
A string value is set in the Session object using the SetString method of the HttpContext.Session property and the View is returned.
public class HomeController : Controller
{
    public IActionResult Index()
    {
        //Set value in Session object.
        HttpContext.Session.SetString("Message", "Hello Core!");
 
        return View();
    }
}
 
 

View

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 (.Net Core 7), please refer my article .Net Core 7: Using HttpContext in ASP.Net.
 
The value from the Session object is displayed in View using the GetString method of the HttpContext.Session property.
@inject IHttpContextAccessor Accessor
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <div>
        @Accessor.HttpContext.Session.GetString("Message")
    </div>
</body>
</html>
 
 

Screenshot

.Net Core 7: Using Session in ASP.Net Core
 
 

Downloads



Other available versions