Unable to use session in ASP.Net vNext Project
Solution 1
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: https://stackoverflow.com/a/29569746/832546
Fixed code:
public void Configure(IApplicationBuilder app)
{
app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30));
app.UseMvc();
}
Solution 2
Thanks to @acrhistof the link helped.
So if you are using RC1: add this these dependencies in project.json:
"Microsoft.AspNet.Session": "1.0.0-rc1-final",
"Microsoft.Extensions.Caching.Memory": "1.0.0",
in Startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.AddCaching();
services.AddSession();
services.AddMvc();
}
and
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseSession(); //outside of dev if (env.IsDevelopment())
....
}
Solution 3
It seems like things changed once again and the well-known ASP.NET session has to be configured differently in the rc1. (no UseInMemorySession()
or other AppBuilder
methods are related to Session
, now it is added as a service).
In general Session
has to be installed, configured, and then used. All these steps are quite new and somewhat unusual. Moreover, it depends on Cache:
Session is built on top of
IDistributedCache
, so you must configure this as well, otherwise you will receive an error.
The quotation above is from ASP.NET 5 docs. All you need to do is described here: https://docs.asp.net/en/latest/fundamentals/app-state.html#installing-and-configuring-session.
Comments
-
hyde almost 2 years
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 myproject.json
file as well and have configured my application to use session via myStartup.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?