我正在尝试在 .net core webapp 中启用会话。我已尝试按照此处的文档进行操作。但问题是会话没有得到持久化。每个新请求都会生成新的会话 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);
}
}
在 ASP.NET Core 中,会话状态存储在分布式缓存中,您已将其配置为内存中。这与 ASP.NET 中的 In Proc 会话存储基本相同。由于存储在内存中的所有内容都与进程相关联,因此每当进程发生更改时,您的会话存储都会被擦除。
现在,只要您保持应用程序运行,它应该仍然保持请求请求,但特别是如果您在 Visual Studio 中停止/开始调试,您正在终止并重新启动进程,因此,擦除会话。
总而言之,如果您需要持久化会话,则需要使用持久存储,例如 SQL Server 或 Redis。如果您愿意,两者都可以用于开发和生产。有关如何设置持久存储的详细信息,请参阅文档。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句