I’m running an ASP.NET Core 8.0 Web API project and have no issues with the GET
or POST
methods, but with DELETE
, I get this error:
alerts:1 Access to XMLHttpRequest at ‘https://api.mydomain.dom/controller/Delete?id=123’ from origin ‘https://angular.mydomain.dom’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
In my Startup.cs
, I have the following code:
public void ConfigureServices(IServiceCollection services)
services.AddCors(options=>
{
options.AddDefaultPolicy(policy =>
{
policy
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseForwardedHeaders();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
From the docs
The call to UseCors must be placed after UseRouting, but before UseAuthorization. For more information, see Middleware order.
So move your app.UseCors()
below app.UseRouting()
;
2