Error:

Using Blazor WebAssembly app to access .NET 7 WebAPi app. Getting the following error…

Access to fetch at 'https://localhost:xxxxx//api/xxxxxx' from origin 'https://localhost:5001' has been blocked by CORS policy: Request header field xxxxxx is not allowed by Access-Control-Allow-Headers in preflight response.

Fix:

Add the following to the WebAPI app…

builder.Services.AddCors(policy =>
{
    policy.AddPolicy("_myAllowSpecificOrigins", builder =>
     builder.WithOrigins("https://localhost:xxxxx/")
      .SetIsOriginAllowed((host) => true) // this for using localhost address
      .AllowAnyMethod()
      .AllowAnyHeader()
      .AllowCredentials());
});

app.UseCors("_myAllowSpecificOrigins");

References:

https://stackoverflow.com/questions/65858468/access-to-fetch-has-been-blocked-by-cors-policy-blazor-client-web-assembly

Last modified: October 27, 2023

Author

Comments

Write a Reply or Comment