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