繁体   English   中英

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

[英]Can't enable CORS for specific API controllers in ASP.NET Core WebApp targeting netcoreapp3.0

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

<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />

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

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

之后,如果我在我的Configure添加它,它会起作用:

app.UseCors("AllowAll");

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

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

    [Route("init")]
    public JsonResult InitSession() {
        [...]
    }
}

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

考虑以下 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>

摘自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();
        });
    }

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

[EnableCors("AllowAll")]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase

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

  1. 删除不推荐使用的Microsoft.AspNetCore.*,在您的情况下为Microsoft.AspNetCore.Cors 这导致您的.csproj看起来像:
 <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.0</TargetFramework> </PropertyGroup> </Project>
  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(); }); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM