Soledad_Ice
Soledad_Ice

Reputation: 223

.net core 'Response.Cookies.Append' not working as some station

I am using 'Response.Cookies.Append' for setting the culture as suggested in ASP.NET Core 2.1 docs (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-2.1#implement-a-strategy-to-select-the-languageculture-for-each-request).

And it is working perfectly fine at my station. But when my colleague fetches my changes, It is not working.

During debug, I found 'Response.Cookies.Append' didn't add the cookie. Anyone else meets the issue? Any solution?

Upvotes: 22

Views: 30003

Answers (2)

Jindo vu
Jindo vu

Reputation: 21

I use this and it's working for me

HttpContext.Response.Cookies.Append(
                     "name", "value",
                     new CookieOptions() { SameSite = SameSiteMode.Lax });

Upvotes: 2

Erik Mandke
Erik Mandke

Reputation: 1667

You might have a configured CookiePolicyOption in your Startup.cs in your ConfigureServices-Method.

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

If thats the case, you can set the cookie with the CookieOption.IsEssential = true like so:

var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions()
    {
      Path = "/", HttpOnly = false, IsEssential = true, //<- there
      Expires = DateTime.Now.AddMonths(1), 
    };

Update: If you are using SameSiteMode.None, you also have to set the "Secure" property to true. The cookie will work with https only

Alternativly SameSiteMode.Unspecified does work without https/secure-flag

Source: https://learn.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-3.1

Upvotes: 62

Related Questions