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.
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:
var cookieValue = Request.Cookies[cookieName];
(cookieName
is a variable set with name of the 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.
Starting from ASP.NET Core 2.1, the templates include a GDPR compliant configuration of your CookiePolicyOptions
in Startup.cs, namely:
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.
You can either change this behaviour, or mark your cookie as essential by setting the IsEssential
property to true
when creating it:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With