CORS errors when calling your API
Allow your front end to call an API hosted on another domain.
The browser console shows an error such as "has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present" when a front end on one domain calls an API on another domain.
CORS (Cross-Origin Resource Sharing) is always controlled by your API application, not by the hosting. By default a Web API does not allow requests from other origins, so you have to say which front-end addresses are allowed.
Allow your front end in ASP.NET Core
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy("Frontend", policy => policy
.WithOrigins("https://www.example.com") // address of your front end
.AllowAnyHeader()
.AllowAnyMethod());
});
var app = builder.Build();
app.UseCors("Frontend"); // before UseAuthentication / UseAuthorization
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Things that are often wrong
- The origin does not match exactly.
http://andhttps://are different origins, and so areexample.comandwww.example.com. Do not add a slash at the end of the address. - The configuration still points to localhost. Check
appsettings.jsonon the server for addresses such ashttps://localhost:7102left over from development — both the allowed origin in the API and the API address in the front end. - The real error is something else. When the API fails with an error 500, the response has no CORS headers and the browser reports it as a CORS problem. Check the website logs of the API.
- Cookies over HTTP. An authentication cookie marked as Secure is discarded by the browser on an
http://address, so the user appears to be logged out. Enable HTTPS for both websites and usehttps://addresses everywhere.
Still stuck?
Our support team is happy to help.