ASP.NET 核心 2.1
我在一个 Controller 中设置了一个 session 变量:
public ActionResult setsession()
{
HttpContext.Session.SetString("name","Fozzy");
return Ok();
}
当我暂停调试器之后,我可以在此时看到 session 中的值
设置 session 变量。然后,我尝试通过 fetch 立即检索另一个 Controller 中的 session 变量,但它始终为空:
public ActionResult getsession()
{
var fozzy = HttpContext.Session.GetString("name");
// fozzy is null
return Ok(fozzy);
}
我已将 session 超时设置为 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?}");
});
}
我的问题不是设置 session 变量。我经历了那个噩梦。如果设置变量有问题,.Net Core 会抛出异常。我已经克服了这一切。
如何让我的 session 保留 ASP.net Core 2.1 中的值?谢谢
最佳答案
根据 the documentation on session state ,您需要按照三个步骤在 ASP.NET Core 中启用 session :
To enable the session middleware, Startup must contain:
- Any of the
IDistributedCache
memory caches. TheIDistributedCache
implementation is used as a backing store for session. For more information, see Distributed caching in ASP.NET Core.- A call to
AddSession
inConfigureServices
.- A call to
UseSession
inConfigure
.
所以除了
services.AddSession()
设置一般 session 服务以便您可以一般访问它,您还需要执行 services.AddDistributedMemoryCache()
为了有一些地方来存储数据。最后,内部 Configure
您需要使用 app.UseSession()
设置 session 中间件确保在处理请求时读取 session 数据,以便您可以访问先前存储的数据。
关于c# - session 变量立即为空..ASP.net Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55666890/