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

编程入门 行业动态 更新时间:2024-10-23 11:28:51
本文介绍了会话变量值在 ASP.NET Core 中为 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在一个方法中设置一个会话变量,并试图从控制器中的另一个方法获取会话变量值,但它总是为空:

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 中为 null

本文发布于:2023-11-15 23:24:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598880.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中为   变量值   ASP   NET   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!