c# - 会话变量立即为空..ASP.net Core
问题描述
ASP.NET 核心 2.1
我在一个控制器中设置了一个会话变量:
public ActionResult setsession()
{
HttpContext.Session.SetString("name","Fozzy");
return Ok();
}
当我在设置会话变量后暂停调试器时,此时我可以看到会话中的值。然后,我尝试通过 fetch 立即检索另一个控制器中的会话变量,但它始终为空:
public ActionResult getsession()
{
var fozzy = HttpContext.Session.GetString("name");
// fozzy is null
return Ok(fozzy);
}
我已将会话超时设置为 20 分钟(我认为)
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
});
这是我的startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
});
services.AddMvc().AddSessionStateTempDataProvider();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("CorsPolicy");
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(name: "spa-fallback",
defaults: new { controller = "values", action = "Get" });
});
//if (env.IsDevelopment())
//{
// app.UseDeveloperExceptionPage();
//}
//else
//{
// app.UseExceptionHandler("/Home/Error");
// app.UseHsts();
//}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
我的问题是没有设置会话变量。我经历了那个噩梦。如果设置变量有问题,.Net Core 会引发异常。我已经度过了这一切。
如何让我的会话保留 ASP.net Core 2.1 中的值?谢谢
解决方案
根据有关会话状态的文档,您需要按照三个步骤在 ASP.NET Core 中启用会话:
要启用会话中间件,Startup 必须包含:
- 任何
IDistributedCache
内存缓存。该IDistributedCache
实现用作会话的后备存储。有关详细信息,请参阅ASP.NET Core 中的分布式缓存。- 调用
AddSession
inConfigureServices
。- 调用
UseSession
inConfigure
。
因此,除了services.AddSession()
设置通用会话服务以便您可以访问它之外,您还需要这样做services.AddDistributedMemoryCache()
以便有一些地方来存储数据。最后,Configure
您需要在内部设置会话中间件app.UseSession()
,以确保在处理请求时读取会话数据,以便您可以访问先前存储的数据。
推荐阅读
- sublimetext3 - 如何在 Sublime Text 3 中删除我的文本下的这些卷曲下划线?
- python - Scipy:具有阈值的稀疏相似性的ε邻域
- python - 在python中读取文件时出现问题
- sql - 如何处理没有唯一 ID 的插入和重复
- swift - NSWindow 在关闭 NSPopover 后失去了第一响应者
- batch-file - 运行standalone.bat文件时出现“此时意外”错误
- gnuplot - gnuplot 的“lc 调色板”的默认称重标准
- msbuild - 按条件将文件包含到 VS2017 c++ 项目中
- git - 什么会导致 git lfs 对象丢失?
- php - 如何将存储在变量中的代码输出到代码中?