ASP.NET 核心 Web 应用程序找不到 cookie 值。我错过了什么?

ASP.NET Core Web Application cannot find cookie value. What am i missing?

我已经从我的 ASP.NET 网络表单应用程序创建了一个简单的网络 cookie。我正在尝试从 separate.NET 核心网络应用程序中检索此 cookie。每当我尝试这样做时,.NET Core 应用程序都会不断返回 cookie 的空值。

这是在 ASP.NET 网络表单应用程序中创建 cookie 的方式:

 protected void btn1_Click(object sender, EventArgs e)
        {
            HttpCookie Abc = new HttpCookie("Abc");
            DateTime now = DateTime.Now;

            //Abc Set the cookie value.
            Abc.Value = txt1.Text;
            // Set the cookie expiration date.
            Abc.Expires = now.AddMinutes(1);

            // Add the cookie.
            Response.Cookies.Add(Abc);

       }

这就是我尝试从 .NET Core 应用程序读取此 "Abc" cookie 的方式:

public void OnGet()
        {

         if (HttpContext.Request.Cookies["Abc"] != null)
            {
                Message = "ya";
            }
            else
            {
                Message = "no";
            }
        }

这是 ASP.NET CORE 应用的 Startup.cs 详细信息:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddDistributedMemoryCache();
          //  services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddHttpContextAccessor();
            services.AddSession(options =>
            {
                options.Cookie.HttpOnly = true;
                // Make the session cookie essential
                options.Cookie.IsEssential = true;
            });

            services.Configure<CookiePolicyOptions>(options =>
            {
                // No consent check needed here
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSession();
            app.UseRouting();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }

当我 运行 ASP .NET Core 应用程序时,我能够按预期在浏览器中找到 cookie:

我花了好几个小时研究这个但没有成功。关于为什么我无法从 .Net Core 应用程序读取 cookie 的任何想法?我非常感谢任何反馈。

谢谢!

如果您的网络应用托管在同一域的子域中(例如 app1.example.com 和 app2.example.com),那么您可以通过设置 [=13] 轻松读取子域之间的 cookie =] 属性 的 HttpCookie 对象到 .example.com

HttpCookie Abc = new HttpCookie("Abc");
DateTime now = DateTime.Now;
Abc.Domain = ".example.com";
//Abc Set the cookie value.
Abc.Value = txt1.Text;
// Set the cookie expiration date.
Abc.Expires = now.AddMinutes(1);

// Add the cookie.
Response.Cookies.Add(Abc);