本文介绍了会话变量值在 ASP.NET Core 中为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一种方法中设置会话变量,并尝试从控制器中的另一种方法获取会话变量值,但它总是为空:
I am setting a session variable in one method and trying to get the session variable value from the another method in a controller but its always getting null:
这是我的代码:
public class HomeController : Controller
{
public IActionResult Index()
{
HttpContext.Session.SetString("Test", "Hello!");
var message = HttpContext.Session.GetString("Test");// Here value is getting correctly
return View();
}
public IActionResult About()
{
var message = HttpContext.Session.GetString("Test"); // This value is always getting null here
return View();
}
}
这是我在 Startup
类中的会话配置:
Here is my session configuration in Startup
class:
在ConfigureServices()
方法中:
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDistributedMemoryCache();
services.AddMvc().AddSessionStateTempDataProvider();
services.AddSession(options =>
{
options.Cookie.Name = "TanvirArjel.Session";
options.IdleTimeout = TimeSpan.FromDays(1);
});
在Configure()
方法中:
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
很奇怪很奇特的问题!任何帮助将不胜感激!
推荐答案
适用于 ASP.NET Core 2.1 和 2.2
在Startup类的ConfigureServices
方法中,设置options.CheckConsentNeeded = context =>;false;
如下:
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;
});
问题解决了!
这篇关于会话变量值在 ASP.NET Core 中为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!