我正在尝试将我的资产提供到同一个域的子域中。因此,当我的主域是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.css
和my_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?