为什么我在 Angular 中收到 ASP.NET 8.0 CORS 错误

问题描述 投票:0回答:1

我正在运行 ASP.NET 8.0 WebAPI 项目,并且 GET 或 POST 方法没有问题,但使用 DELETE 时,我收到此错误:

警报:1 从源“https://angular.mydomain.dom”访问“https://api.mydomain.dom/controller/Delete?id=123”处的 XMLHttpRequest 已被 CORS 策略阻止:无“访问” -Control-Allow-Origin'标头存在于请求的资源上。

在我的 Startup.cs 中,我实现了以下功能:

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.UseCors();
    app.UseForwardedHeaders();
    app.UseHttpsRedirection();
    app.UseRouting();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
c# cors .net-8.0
1个回答
0
投票

来自文档

对 UseCors 的调用必须放在 UseRouting 之后、UseAuthorization 之前。有关更多信息,请参阅中间件顺序。

所以将你的

app.UseCors()
移到
app.UseRouting()
下方;

© www.soinside.com 2019 - 2024. All rights reserved.