无法在ASP.Net vNext项目中使用会话
我有一个使用Session的ASP.Net vNext项目。 但是我在尝试获取/设置会话中的值时收到此错误。
Microsoft.AspNet.Http.Core.dll中出现“System.InvalidOperationException”类型的exception,但未在用户代码中处理
附加信息:尚未为此应用程序或请求配置会话。
这是我的控制器方法:
[AllowAnonymous] [HttpGet("/admin")] public IActionResult Index() { if (Context.Session.GetString("UserName") == null) // error thrown here { return RedirectToAction("Login"); } return View(); }
我在我的project.json
文件中添加了KVM软件包"Microsoft.AspNet.Session": "1.0.0-beta3"
,并将我的应用程序配置为通过我的Startup.cs
使用session,如下所示:
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)); }
我查看了Github上的vNext文档,但它没有提供有关ASP.Net会话的大量信息。 我究竟做错了什么?
所以我想出来了。 实际上修复非常简单。 由于ASP.Net将中间件顺序添加到请求管道中,我所需要做的就是在使用MVC之前使用会话中间件。 更多信息: https : //stackoverflow.com/a/29569746/832546
固定代码:
public void Configure(IApplicationBuilder app) { app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30)); app.UseMvc(); }
感谢@acrhistof链接帮助。
所以如果你使用RC1:在project.json中添加这些依赖项:
"Microsoft.AspNet.Session": "1.0.0-rc1-final", "Microsoft.Extensions.Caching.Memory": "1.0.0",
在Startup.cs文件中:
public void ConfigureServices(IServiceCollection services) { services.AddCaching(); services.AddSession(); services.AddMvc(); }
和
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseSession(); //outside of dev if (env.IsDevelopment()) .... }
似乎事情再次发生变化,众所周知的ASP.NET会话必须在rc1中进行不同的配置。 (没有UseInMemorySession()
或其他AppBuilder
方法与Session
相关,现在它被添加为服务)。
通常,必须安装,配置然后使用Session
。 所有这些步骤都是新的,有点不寻常。 而且,它取决于Cache:
Session建立在
IDistributedCache
,因此您也必须配置它,否则您将收到错误。
上面的引用来自ASP.NET 5文档。 您需要做的就是在这里描述: https : //docs.asp.net/en/latest/fundamentals/app-state.html#installing-and-configuring-session 。