Mvc icon indicating copy to clipboard operation
Mvc copied to clipboard

Read session variable in cshtml results in error

Open giddev opened this issue 11 years ago • 2 comments

Packages.json

"Microsoft.AspNet.Http": "1.0.0-beta8",
"Microsoft.AspNet.Session": "1.0.0-beta8",

View _Layout.cshtml

@using Microsoft.AspNet.Http;

and

@{
    int? myInt= Context.Session.GetInt32("myInt");
}

Run

InvalidOperationException: Session has not been configured for this application or request.
Microsoft.AspNet.Http.Internal.DefaultHttpContext.get_Session()
Asp.ASPV__Views_Shared__Layout_cshtml.<ExecuteAsync>d__26.MoveNext() in    _Layout.cshtml
        int? myInt= Context.Session.GetInt32("myInt");
--- End of stack trace from previous location where exception was thrown ---

Changing it to a set

Context.Session.SetInt32("myInt",1);

gives the same error

giddev avatar Oct 19 '15 12:10 giddev

You have to add the session feature to your application in the Startup class:

public void ConfigureServices(IServiceCollection services)
{
   // ...
   services.AddSession();
   // ...
}

public void Configure(IApplicationBuilder app)
{
   // ...
   app.UseSession();
   // ...
}

henkmollema avatar Oct 19 '15 12:10 henkmollema

Thanks forgot I commented it out when troubleshooting.

giddev avatar Oct 19 '15 12:10 giddev