'Cookies are not set in .NET6 WebApi application

For some reason my cookies are not being set. I have tried several things, but my cookie never appears to be set when I check the Cookie storage in Chrome or Edge.

In my Startup.cs I have the following:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;

        // Also tried SameSiteMode.None
        options.MinimumSameSitePolicy = SameSiteMode.Lax;
    });

    ... 
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseCors(options => options
            .WithOrigins("http://localhost:3000")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
        app.UseCookiePolicy(); // Breakpoint hits this code
    }

    ...
}

Then in my Controller Action I try to set the cookie:

public IActionResult Test()
{
    // Also tried different SameSiteMode options, non seem to work.
    // If I set a breakpoint, then it hits. So code gets executed.
    HttpContext.Response.Cookies.Append("X-Blaat", "test", new CookieOptions { Expires = 
    DateTime.UtcNow.AddMonths(1), SameSite = SameSiteMode.Lax, IsEssential = true});

    return Ok();
}

This Web API runs on https://localhost:44365. The endpoint lives on: https://locahost:44365/api/test.

I call this endpoint through a React application which runs on http://localhost:3000.

But for some reason my cookie never gets set. Eventhough I can debug through the code.

Anyone any idea why my cookie never gets written to the browser?

Update

When I call the same endpoint through Swagger, then the cookies do get set.

For some reason they are not appearing when I call my Web API through my React application.

I suspect the issue is that it runs on a different port than my Web API. Is there anything I can try to solve this issue?



Solution 1:[1]

I assume you already figure it out. But the problem is that you are trying to set cookie from https to http. If you remove in the program.cs the line app.UseHttpsRedirection(); And in your client use the http version of the api, should work)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Csala