我正在尝试在同一个域的子域中提供我的资产。因此,当我的主要域名是https://localhost:44111/
资产网址时,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
该请求时,则被禁止。
我试图按照文档启用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网址不能以/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句