ASP.NET 5: Access-Control-Allow-Origin 响应

ASP.NET 5: Access-Control-Allow-Origin in response

据我了解,相应地启用 CORS 后,响应模型应包含以下 header 信息(前提是我要允许所有内容):

Access-Control-Allow-Origin: *
Access-Control-Allow-Method: *
Access-Control-Allow-Header: *

Startup中启用它:

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //...
    app.UseCors("AllowAll");
    //...
}

问题是这些 header 中的 none 被返回,我在尝试从 API 请求时收到以下错误:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

确保在 Startup.Configure 方法中的 app.UseMvc 之前添加 app.UseCors,因为您需要在 MVC 中间件之前应用 CORS 中间件。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ...

    //Add CORS middleware before MVC
    app.UseCors("AllowAll");

    app.UseMvc(...);
}

否则请求会在应用CORS中间件之前完成。这是因为 UseMvc calls UseRouter which ends up adding the RouterMiddleware,并且此中间件仅在找不到请求的路由处理程序时才执行下一个配置的中间件。

在 .Net Core Web API 5.0 的 Configure 方法中,您必须在其他方法之前添加 app.UseCors,例如:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        ...
    }

    //add CORS
    app.UseCors();

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}