无法在ASP.Net vNext项目中使用会话 [英] Unable to use session in ASP.Net vNext Project
问题描述
我有一个使用Session的ASP.Net vNext项目.但是我在尝试获取/设置会话中的值时遇到此错误.
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.
Microsoft.AspNet.Http.Core.dll中发生类型'System.InvalidOperationException'的异常,但未在用户代码中处理
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.
这是我的控制器方法:
[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
使用会话,如下所示:
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));
}
我看过Github上的vNext文档,但是它没有提供有关ASP.Net会话的大量信息.我在做什么错了?
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?
推荐答案
所以我弄清楚了.解决方法实际上非常简单.由于ASP.Net将中间件顺序地添加到请求管道中,因此我需要做的就是在使用MVC之前使用会话中间件.此处的更多信息: https://stackoverflow.com/a/29569746/832546
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
固定代码:
public void Configure(IApplicationBuilder app)
{
app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30));
app.UseMvc();
}
这篇关于无法在ASP.Net vNext项目中使用会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!