hyde hyde - 3 months ago 18
ASP.NET (C#) Question

Unable to use session in ASP.Net vNext Project

I have an ASP.Net vNext project that uses Session. But I am getting this error while trying to get/set values in the session.


An exception of type 'System.InvalidOperationException' occurred in Microsoft.AspNet.Http.Core.dll but was not handled in user code

Additional information: Session has not been configured for this application or request.


Here's my controller method:

[AllowAnonymous]
[HttpGet("/admin")]
public IActionResult Index()
{
if (Context.Session.GetString("UserName") == null) // error thrown here
{
return RedirectToAction("Login");
}

return View();
}


I have added the KVM package
"Microsoft.AspNet.Session": "1.0.0-beta3"
in my
project.json
file as well and have configured my application to use session via my
Startup.cs
like so:

public void ConfigureServices(IServiceCollection services)
{
// code removed for brevity
services.AddCachingServices();
services.AddSessionServices();
}

public void Configure(IApplicationBuilder app)
{
app.UseMvc();
app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30));
}


I have looked at the vNext documentation on Github but it does not provide much information about ASP.Net sessions. What am I doing wrong?

Answer

So I figured this out. The fix was quite simple actually. Since ASP.Net adds the middlewares sequentially into the request pipeline, all I needed to do was use the session middleware before using MVC. More info here: http://stackoverflow.com/a/29569746/832546

Fixed code:

public void Configure(IApplicationBuilder app)
{
    app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30));
    app.UseMvc();
}
Comments