【发布时间】:2018-09-18 15:08:43
【问题描述】:
我正在尝试在 .net core webapp 中启用会话。我尝试按照here 的文档进行操作。但问题是会话没有得到持续。即使先前的请求已在会话中存储了某些内容,也会随着每个新请求生成新的会话 ID。我也没有在开发工具中看到任何 cookie。
引用的 dll
"Microsoft.AspNetCore.Session": "1.1.1",
"Microsoft.Extensions.Caching.Memory": "1.1.1"
我的启动文件看起来像这样
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc(options => { options.Filters.Add(new RequireHttpsAttribute()); });
// Add services needed for sessions
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
});
// Add in-memory distributed cache
services.AddDistributedMemoryCache();
// initialising other services, authentication and authorization policies
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// enable session before uisng it in pipeline
app.UseSession();
// setting custom user middleware
app.UseUserMiddleware();
// set up the mvc default route
app.UseMvc(routes => { routes.MapRoute("default", "myDefaultRoute"); });
// adding few other middlewares
}
然后我在我的控制器中设置和访问会话值,就像这样
public class MyController : Controller
{
private const string Key = "someKey";
public async Task<ResponseModel> Get()
{
var id = HttpContext.Session.GetInt32(Key);
return new ResponseModel(await _myService.GetAsync(id));
}
public async Task Set([FromBody] RequestModel request)
{
var id = await _myService.GetAsync(request.id);
HttpContext.Session.SetInt32(Key, id);
}
}
【问题讨论】:
-
在开发工具的响应头中有cookie吗?
-
什么是UseUserMiddleware?删除后还有问题吗?
标签: c# session asp.net-core .net-core