Header add

In this article we will learn about Enable Session in ASP.Net Core.

By default, Session State is disabled in ASP.Net Core applications i.e. ASP.Net Core MVC and ASP.Net Core Razor Pages.

This article will cover the steps to enable Session Sate in ASP.Net Core applications.



Prerequisites

  • I have used Visual Studio 2022 ( You can downgrade it )
  • .NET Core 5 SDK ( You can downgrade or Upgrade it )

How to enable Session in ASP.Net Core in Startup.cs file

Setting the Session Timeout

We declared AddSession method of the services object inside ConfigureServices file.

The AddSession can be called directly without any parameters and it can also be used to set the IdleTimeout property which sets the Session Timeout duration.



Enabling the Session

Session can be enabled using the Configure method. Inside this method, you will have to call the UseSession method.

app.UseSession();

app.useSession



Get and Set Session in Controller

On the below part it consists of the following two Action methods.

Action method for handling GET operation

Inside this Action method, Session object is set and the View is returned.
The Session object is set using the SetString method of the HttpContext.Session property.
 
Action method for handling POST operation

Inside this Action method, the Session variable name is received as parameter in POST method. Then the value of the Session object is fetched and assigned to ViewBag object.



View

The View consists of an HTML Form with following ASP.Net Tag Helpers attributes.

asp-action – Name of the Action. In this case the name is Index.
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.

When the Get Session Button is clicked, the Form gets submitted and the value of TextBox is sent to the Controller. Finally, the value of the Session object is displayed in the Label.




Output

Post a Comment

Previous Post Next Post