Header add

In this article we will learn about Session has not been configured for this application or request.

In some cases we got the error like System.InvalidOperationException: Session has not been configured for this application or request.

The above error occurs when Session state is used in ASP.Net Core application without configuring the application. In the below example we discuss how to get rid of this.



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