In this article we will learn about Get and Set Session variable in ASP.Net Core.
Session is use in ASP.Net core is different way we will discuss it in this article, In typical ASP.Net and ASP.Net MVC we use session like session["MySession"].
Prerequisites
- I have used Visual Studio 2022 ( You can downgrade it )
- .NET Core 5 SDK ( You can downgrade 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();
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