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

我正在尝试将我的资产提供到同一个域的子域中。因此,当我的主域是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');
}

当我包含资产子域中的style.css文件时,出现以下错误

  

跨域请求被阻止:“同源起源”策略禁止读取https://assets.localhost:44111/css/fonts/my_custom_font.eot?123处的远程资源。 (原因:CORS标头“ access-control-allow-origin”缺失)。

为确保清楚,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?

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

WithOrigins(string[])接受字符串参数(字符串数组,string [])。这允许您执行以下操作:

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

注意:请不要忘记cors网址不能以/结尾

本文链接:https://www.f2er.com/3150464.html

大家都在问