简体   繁体   English

.Net Core cookie 不会被设置

[英].Net Core cookie will not be set

In .Net Core MVC project: I'm trying to set a simple cookie in the easiest way in my controller-action but can not get it to be persistent and show up in the browser.在 .Net Core MVC 项目中:我试图在我的控制器操作中以最简单的方式设置一个简单的 cookie,但无法使其持久化并显示在浏览器中。

My code:我的代码:

public IActionResult IndexPost()
{
    var option = new CookieOptions();
    option.Expires = DateTime.Now.AddMinutes(60);
    Response.Cookies.Append(cookieName, "SomeCookieValue", option);
    return View();
}

But in the browser (Chrome) I can't see it or even read it with:但是在浏览器(Chrome)中,我看不到它,甚至无法使用以下命令阅读它:

var cookieValue = Request.Cookies[cookieName];

( cookieName is a variable set with name of the cookie) cookieName是一个带有 cookie 名称的变量集)

If using Chrome extension "EditThisCookie" I can set it manually to ensure that Request.Cookies[cookieName] actually works, so error is in the Append-cookie of my code somehow.如果使用 Chrome 扩展“EditThisCookie”,我可以手动设置它以确保Request.Cookies[cookieName]确实有效,所以错误在我的代码的 Append-cookie 中。

Starting from ASP.NET Core 2.1, the templates include a GDPR compliant configuration of your CookiePolicyOptions in Startup.cs, namely:从ASP.NET 2.1的核心开始,该模板包括你的GDPR兼容配置CookiePolicyOptions在Startup.cs,即:

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;
});

The CheckConsentNeeded option of true will prevent any non-essential cookies from being sent to the browser (no Set-Cookie header) without the user's explicit permission. CheckConsentNeeded选项为true将防止在未经用户明确许可的情况下将任何非必要的 cookie 发送到浏览器(无 Set-Cookie 标头)。

You can either change this behaviour, or mark your cookie as essential by setting the IsEssential property to true when creating it:您可以更改此行为,或通过在创建时将IsEssential属性设置为true来将您的 cookie 标记为必需:

var options = new CookieOptions
{
    Expires = DateTime.Now.AddMinutes(60),
    IsEssential = true
};

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

Read more here: https://docs.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-2.1在此处阅读更多信息: https : //docs.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-2.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM