.Net Core cookie will not be set
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
Related videos on Youtube
Comments
-
Persyl over 1 year
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.-
Sigge over 5 yearsHave you checked Chrome's network tab in the developer options? You should see the IndexPost request setting the cookie header there.
-
-
Persyl over 5 yearsYeah, thanks! That worked! Strange I have not seen this anywhere in my search for answer.
-
Marinpietri over 3 yearsSorry, but if you have connection HTTPS that's works fine. in my test I thats was the correct way.
-
Garry almost 3 yearsPerfect, This is what I was missing.