Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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.

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.

like image 215
Persyl Avatar asked Sep 22 '18 11:09

Persyl


1 Answers

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

like image 104
Sigge Avatar answered Oct 01 '22 23:10

Sigge