上QQ阅读APP看书,第一时间看更新
CORS
If you see the following error when you call the API action, then you need to enable Cross Origin Resource Sharing (CORS):
Failed to load http://localhost:57571/api/Customers: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.
To enable CORS for all origins, follow the steps shown ahead:
- Install the Microsoft.AspNetCore.Cors NuGet package:
- Inside Startup ConfigureServices, add the following code to implement a policy for CORS that would allow all origins:
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
- Inside the Configure method, add the following line before app.UseMvc(); (it's important):
app.UseCors("AllowAll");
Now, it should work as expected. If you want to explore CORS more, visit https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1.