C# 如何从Razor视图中的会话中获取价值?

C# 如何从Razor视图中的会话中获取价值?,c#,asp.net-mvc,C#,Asp.net Mvc,在核心2.1中: 我在控制器中设置值 HttpContext.Session.SetString("IsAuthenticated", "true"); 当我在view.cshtml中获得该值时,该值为null if (Context.Session.GetString("IsAuthenticated") == "true") 我刚刚在我的一个应用程序中运行了你的代码,它运行正常。在我看来,你还没有在你的应用程序中设置cookies的使用。请尝试以下操作: // The following

在核心2.1中: 我在控制器中设置值

HttpContext.Session.SetString("IsAuthenticated", "true");
当我在view.cshtml中获得该值时,该值为null

if (Context.Session.GetString("IsAuthenticated") == "true")

我刚刚在我的一个应用程序中运行了你的代码,它运行正常。在我看来,你还没有在你的应用程序中设置cookies的使用。请尝试以下操作:

// The following goes into ConfigureServices in Startup.cs
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(5);
    options.Cookie.HttpOnly = true;
});
完成后,您还需要在Startup.cs中的
Configure
方法中设置它

// place after the other app.UseFoo methods. 
app.UseSession(); 

您可以访问该页面以了解更多信息:当然,我已将此添加到Startup,但这是无用的@极好的