会话变量值在ASP.NET Core中变为null

Tan*_*jel 31 session session-variables asp.net-core-mvc asp.net-core

我在一个方法中设置一个会话变量,并尝试从控制器中的另一个方法获取会话变量值,但它始终为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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我在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);
});
Run Code Online (Sandbox Code Playgroud)

Configure()方法中:

app.UseSession();
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});
Run Code Online (Sandbox Code Playgroud)

非常奇怪和特殊的问题!任何帮助将非常感谢!

Tan*_*jel 73

对于ASP.NET Core 2.1和2.2

ConfigureServicesStartup类的方法中,设置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;
});
Run Code Online (Sandbox Code Playgroud)

问题解决了!

  • 不为我工作。还有什么我可以做的吗? (8认同)
  • 但这不是表示 CheckConsentNeeded 默认为 false 吗?https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.cookiepolicyoptions.checkconsentneeded?view=aspnetcore-2.2 (2认同)

Max*_*lli 8

您也可以Cookie.IsEssential = true按照此处的说明进行设置:https : //andrewlock.net/session-state-gdpr-and-non-essential-cookies/

有一个重载services.AddSession()允许您SessionOptionsStartup文件中进行配置。您可以更改会话超时等各种设置,还可以自定义会话 cookie。要将 cookie 标记为必需,请设置IsEssential为 true:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true; // consent required
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddSession(opts => 
    {
        opts.Cookie.IsEssential = true; // make the session cookie Essential
    });
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
Run Code Online (Sandbox Code Playgroud)