I've setup an Aspire solution with a Blazor WebAssembly and an API projects. API runs on https://localhost:7476 and Blazor is served from https://localhost:7077. Generally any API registered with MapPost
or MapGet
is working as expected because by default Blazor app runs in InteractiveServer mode, so all APIs appear to be called via internal SignalR connection.
However for uploading files from the web, I need to hit the API endpoint directly. I'm using RadzenUpload
component to do so, and I've configured it to hit https://localhost:7476/api/upload
However the browser gives me an error:
Access to XMLHttpRequest at 'https://localhost:7476/api/upload' from origin 'https://localhost:7077' 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.
I've tried adding the following to both the API and the Blazor's Program.cs but that didn't help. Any help is greatly appreciated.
builder.Services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
...
var app = builder.Build();
app.UseCors("AllowAll");
The error indicates the response from server lacks header Access-Control-Allow-Origin
(which would be appended by app.UseCors()
middleware), So you don't have to add the cors related codes in your blazor app,just add the codes in your webapi project
Also,try modify your policy to
builder.Services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.WithOrigins("https://localhost:{port of your blazor app}")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
......
app.UseCors("MyPolicy");
if you are working on controller based webapi,notice the order of the middleware,follow the sample in official document
It now works on myside: