【问题标题】:Cookie after append is null in ASP.NET Core 3.1 MVC在 ASP.NET Core 3.1 MVC 中追加后的 Cookie 为空
【发布时间】:2021-04-11 04:54:53
【问题描述】:

我有创建 cookie 的代码,如您所见,并向其附加值:

Response.Cookies.Append("rudeCookie", "I don't need no user to tell me it's ok.", options);
var AccessToken = Request.Cookies["rudeCookie"];

追加后,Request.Cookies["rudeCookie"] 的值为 null - 为什么?

这是我的startup 文件:

public void ConfigureServices(IServiceCollection services)
{ 
    services.AddMvc();
    services.AddControllersWithViews();
           
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddScoped<saamieServices.IComplicationClient, saamieServices.ComplicationClient>();
    services.AddScoped<saamieServices.IIdentityClient, saamieServices.IdentityClient>();

    // 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.ConfigureApplicationCookie(option =>
            {
                option.Cookie.Name = "User";
                option.LoginPath = "User/UserRegister";
            });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
}

【问题讨论】:

  • 如果您的代码与您在此处提供的完全一样,这是正常的。 Request.Cookies 显示作为当前请求的一部分提供的 cookie,并且不会包含通过 Response.Cookies 编写的 cookie,直到您的 下一个 请求——当这些 cookie 通过请求发送时。这很令人困惑,因为您可能会认为它们指的是同一个集合。

标签: .net cookies asp.net-core-3.1 setcookie


【解决方案1】:

据我所知,cookie 基于浏览器并在客户端浏览器加载后被初始化。

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 2021-12-26
    • 2021-04-14
    • 2021-02-26
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    相关资源
    最近更新 更多