会话变量值在ASP.NET Core中为空 [英] Session variable value is getting null in ASP.NET Core

查看:119
本文介绍了会话变量值在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()方法中:

In ConfigureServices() method:

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()方法中:

In Configure() method:

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;:

For ASP.NET Core 2.1 and 2.2

In the ConfigureServices method of the Startup class, Set options.CheckConsentNeeded = context => false; as follows:

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中为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆