无法为面向 netcoreapp3.0 的 ASP.NET Core WebApp 中的特定 API 控制器启用 CORS

Jez*_*Jez 2 c# cors asp.net-core asp.net-core-3.0

我正在尝试为 ASP.NET Core 应用程序中的特定 API 控制器启用 CORS。首先,我安装 NuGet 包,并将其添加到我的.csproj

<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
Run Code Online (Sandbox Code Playgroud)

然后,我在我的中添加以下内容ConfigureServices

services.AddCors(options => {
    options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
Run Code Online (Sandbox Code Playgroud)

之后,如果我将其添加到 my 中Configure,它会起作用:

app.UseCors("AllowAll");
Run Code Online (Sandbox Code Playgroud)

但是,这会为所有控制器启用 CORS。我只想为SessionApiController. 如果我改为添加EnableCorsAttribute到控制器:

[Route("api/session")]
[EnableCors("AllowAll")]
[ApiController]
public class SessionApiController : Controller {
    [...]

    [Route("init")]
    public JsonResult InitSession() {
        [...]
    }
}
Run Code Online (Sandbox Code Playgroud)

...它不起作用,当我尝试访问/api/session/init端点时,Chrome 给我一个 CORS 错误(“请求的资源上不存在‘Access-Control-Allow-Origin’标头。”)。我在这里缺少什么?

Jot*_*edo 6

考虑以下 ASP.NET Core WebApp:

应用程序.csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
  </ItemGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)

摘自Startup.cs

    public void ConfigureServices(IServiceCollection services) {
        services.AddCors(options => {
            options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        });

        services.AddControllers();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
        app.UseCors();  // Doesn't work
        //app.UseCors("AllowAll");  // Works

        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints => {
            endpoints.MapControllers();
        });
    }
Run Code Online (Sandbox Code Playgroud)

从要应用AllowAll策略的控制器中提取:

[EnableCors("AllowAll")]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
Run Code Online (Sandbox Code Playgroud)

为了在其中正确应用 CORS,您需要将以下更改应用到代码中,如迁移 MS 文档中所述

  1. 在您的情况下,删除不推荐使用的Microsoft.AspNetCore.*软件包Microsoft.AspNetCore.Cors。这导致您.csproj看起来像:
 <Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
      <TargetFramework>netcoreapp3.0</TargetFramework>
    </PropertyGroup>
  </Project>
Run Code Online (Sandbox Code Playgroud)
  1. 仔细遵循msdocs 中的中间件迁移建议,因为顺序很重要!. 结果Startup#Configure如下:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();
    
        // AFAIK in netcoreapp2.2 this was not required
        // to use CORS with attributes.
        // This is now required, as otherwise a runtime exception is thrown
        // UseCors applies a global CORS policy, when no policy name is given
        // the default CORS policy is applied
        app.UseCors(); 
    
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
        }
    
        app.UseHttpsRedirection();
    
        app.UseAuthorization();
    
        app.UseEndpoints(endpoints => {
            endpoints.MapControllers();
        });
    }
    
    Run Code Online (Sandbox Code Playgroud)