如何在 ASP.NET Core 2.2 项目中为子域正确启用 CORS?

How to correctly enable CORS for a subdomain in an ASP.NET Core 2.2 project?

我正在尝试在同一域的子域上提供我的资产。因此,当我的主域是 https://localhost:44111/ 时,资产 URL 将类似于 https://assets.localhost:44111/css/style.css

style.css 文件请求包含自定义字体 my_custom_font.eot,就像这样

@font-face {
    ....
    src: url('/css/fonts/my_custom_font.eot?123');
}

当我包含位于 assets 子域的 style.css 文件时,出现以下错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://assets.localhost:44111/css/fonts/my_custom_font.eot?123. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

为了确保我清楚,style.cssmy_custom_font.eot 都位于同一个域 assets.localhost:44111。包含 style.css 的请求没有问题。但是,当 style.css 请求包含 my_custom_font.eot 时,该请求被禁止。

我尝试按照 documentation 启用 CORS。我将以下代码添加到 Startup.ConfigureServices(IServiceCollection services) 方法

services.AddCors(options =>
{
    options.AddPolicy("AllowSubDomainTraffic",
    builder =>
    {
        builder.WithOrigins("https://assets.localhost:44111")
               .AllowAnyHeader()
               .AllowAnyMethod();
    });
});

然后在Startup.Configure(IApplicationBuilder app, IHostingEnvironment env)方法中我添加了下面的

app.UseCors("AllowSubDomainTraffic");

但是,我仍然在浏览器的控制台中收到 CORS header ‘Access-Control-Allow-Origin’ missing 错误。

这就是我在我的应用程序中响应子域的方式

app.MapWhen(context => {
    return context.Request.Host.Value.StartsWith("assets.", StringComparison.OrdinalIgnoreCase)
} (appBuilder) =>
{
    appBuilder.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider("C:/assets"),
    });
});

如何为子域正确启用 CORS?

WithOrigins(string[]) 接受一个字符串参数(字符串数组,string[])。这使您可以:

builder.WithOrigins("https://localhost:44111", "https://assets.localhost:44111")
  .AllowAnyHeader()
  .AllowAnyMethod();

注意:不要忘记cors url不能以/

结尾