I am building a Blazor Web Assembly application with an ASP.NET Core Web API. Now I have set windowsauthentication to true because I want to use a single sign-on. Once I did that I am getting this CORS error with all my API calls. Then I have added BrowserRequestCredentials.Include my httpClient in my Blazor app. Now my GET requests to the API are working but POST, PUT and DELETE still gives me the CORS error in the browser console:
Access to fetch at 'https://localhost:44305/api/user/3' from origin 'https://localhost:4001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
if I test my PUT, POST, and DELETE APIs with swagger, there is no problem.
API startup - configureServices:
services.AddCors(options =>
{
string cors = Configuration["Cors"];
options.AddPolicy("AllowAll",
builder =>
{
builder.WithOrigins(cors.Split(","))
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
options.DefaultPolicyName = "AllowAll";
});
API startup - configure:
app.UseCors("AllowAll");
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("../swagger/v1/swagger.json", "Gmh.Api v1"));
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Blazor WASM app - program.cs
builder.Services.AddTransient(sp => new HttpClient(new DefaultBrowserOptionsMessageHandler(new HttpClientHandler()) // or new HttpClientHandler() in .NET 5.0
{
DefaultBrowserRequestCache = BrowserRequestCache.NoStore,
DefaultBrowserRequestCredentials = BrowserRequestCredentials.Include,
DefaultBrowserRequestMode = BrowserRequestMode.Cors,
})
{
BaseAddress = new Uri(builder.Configuration["Backend:BaseAddress"]),
});