我在一个方法中设置了一个会话变量,然后在控制器的另一个方法中尝试获取会话变量的值,但总是获取到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
类中的会话配置:
在 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?}");
});
非常奇怪和特别的问题!任何帮助将不胜感激!
app.UseSession();
帮助我掌握了会话,谢谢。 - vandsh