Blazor Standalone App doesn’t save HTTP request cookies

I got a .NET 8 Blazor WebAssembly Standalone App that talks to a .NET 8 ASP.NET Core Web API. When an API endpoint adds a cookie to the response, there is no Set-Cookie header in the Blazor App response, document.cookie is empty and when calling another endpoint with the same HttpClient on the same page, the API request doesn’t have the cookie either. Yet when looking at the browser (Edge) inspect Network tab, the response has a Set-Cookie header with the right cookie.

The API code.

Program:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(
    options => options.AddPolicy(
        "wasm",
        policy => policy.WithOrigins([
            "https://localhost:7211", "https://localhost:7171"])
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()));

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors("wasm");
app.UseHttpsRedirection();
app.MapControllers();

app.Run();

CookieController:

[ApiController]
[Route("api/[controller]/[action]")]
public class CookieController : ControllerBase
{
    [HttpGet]
    public async Task<ActionResult> SetCookie()
    {
        var options = new CookieOptions
        {
            HttpOnly = false,
            Secure = true,
            SameSite = SameSiteMode.None
        };
        Response.Cookies.Append("MyCookie", "Testing", options);
        return Ok();
    }

    [HttpGet]
    public async Task<ActionResult> CheckCookie()
    {
        return Request.Cookies.Count > 0 ? Ok() : BadRequest();
    }
}

launchSettings:

{
  "profiles": {
    "https": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "dotnetRunMessages": true,
      "applicationUrl": "https://localhost:7211;http://localhost:5266"
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
}

The blazor app.

Program:

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddSingleton(sp =>
    new HttpClient { BaseAddress = new Uri("https://localhost:7171") }); // Frontend
builder.Services.AddHttpClient("API", client =>
    client.BaseAddress = new Uri("https://localhost:7211")); // Backend

builder.Services.AddSingleton<CookieService>();

await builder.Build().RunAsync();

CookieService:

public class CookieService
{
    private static string MAP_GROUP = "/api/Cookie";
    private HttpClient httpClient;

    public CookieService(IHttpClientFactory httpClientFactory)
    {
        httpClient = httpClientFactory.CreateClient("API");
    }

    public async Task<bool> SetCookie()
    {
        var response = await httpClient.GetAsync($"{MAP_GROUP}/SetCookie");
        return response.IsSuccessStatusCode;
    }

    public async Task<bool> CheckCookie()
    {
        var response = await httpClient.GetAsync($"{MAP_GROUP}/CheckCookie");
        return response.IsSuccessStatusCode;
    }
}

launchSettings:

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "https": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
      "applicationUrl": "https://localhost:7171;http://localhost:5170",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Home.razor:

@page "/"
@using CookieTest.Services

<button class="btn btn-primary" @onclick=Test>Test</button>

@if (checkCookieResult.HasValue)
{
    <div>@setCookieResult</div>
    <div>@checkCookieResult</div>
}

@code {
    [Inject]
    private CookieService cookieService { get; set; }
    private bool? setCookieResult;
    private bool? checkCookieResult;

    private async Task Test()
    {
        setCookieResult = await cookieService.SetCookie();
        checkCookieResult = await cookieService.CheckCookie();
    }
}

When pressing the Test button, setCookieResult is true and checkCookieResult false. I tested with Postman calling https://localhost:7211/api/Cookie/SetCookie and then CheckCookie and it shows the cookie and returns 200 there. So I don’t think it’s the API.

I also tested the same code on a .NET 8 Blazor Web App with rendermode WebAssembly with the only difference being that I can use the frontend url (7171) for the API requests and don’t need to specify a CORS policy. It works there and the cookie is added to document.cookie.

Note that the CookieOptions sets HttpOnly to false and SameSite to None. Secure is true but all urls use https and both projects are launched in https. Also note that the CORS policy allows any method, any header and credentials.

What could possibly make the Blazor App CookieService httpClient with the backend BaseAddress not receive or ignore the MyCookie cookie in the SetCookie endpoint response? Any tips for further testing/debugging is also appreciated.

Edit:
The Blazor App has the Microsoft.Extensions.Http package for the builder.Services.AddHttpClient method and the IHttpClientFactory service. Unintsalling it, giving the HttpClient singleton the backend BaseAddress and injecting it in CookieService instead of the httpClientFactory didn’t solve anything.

Edit2:
Using a JS fetch with credentials include works, so I’m pretty confident it’s the HttpClient not accepting cookies. But then why does the same class accept them in the Blazor Web App with rendermode WebAssembly? Just because the BaseAddress is the same as the builder.HostEnvironment? The HttpClientHandler UseCookies and CookieContainer are not supported in WASM btw.

I finally found the answer!

You need to set the credentials (e.g. cookies) to Include on every request you send. You can do this with a custom DelegatingHandler:

public class CookieDelegatingHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.SetBrowserRequestCredentials(BrowserRequestCredentials.Include);
        request.Headers.Add("X-Requested-With", ["XMLHttpRequest"]);
        return base.SendAsync(request, cancellationToken);
    }
}

Program:

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddTransient<CookieDelegatingHandler>(); // Add the handler as a service

builder.Services.AddSingleton(sp =>
    new HttpClient() { BaseAddress = new Uri("https://localhost:7171") });
builder.Services.AddHttpClient("API", client =>
    client.BaseAddress = new Uri("https://localhost:7211"))
    .AddHttpMessageHandler<CookieDelegatingHandler>(); // Connect the handler to the HttpClient

builder.Services.AddSingleton<CookieService>();

await builder.Build().RunAsync();

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật