【发布时间】:2016-11-03 15:05:14
【问题描述】:
我有一个 ASP .NET Core 自托管项目。我正在从静态文件夹中提供内容(没问题)。它可以毫无问题地跨站点提供图像(显示 CORS 标头)。但是,对于某些文件类型,例如 JSON,它们不会显示 CORS 标头,并且客户端站点无法看到内容。如果我将文件重命名为未知类型(例如 JSONX),它将使用 CORS 标头提供服务,没问题。我怎样才能让这个东西用 CORS 标头提供所有内容?
我在 Startup.cs 中设置了以下 CORS 策略:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials() );
});
// Add framework services.
services.AddMvc();
}
以下是我的配置
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("CorsPolicy");
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
// Static File options, normally would be in-line, but the SFO's file provider is not available at instantiation time
var sfo = new StaticFileOptions() { ServeUnknownFileTypes = true, DefaultContentType = "application/octet-stream", RequestPath = "/assets"};
sfo.FileProvider = new PhysicalFileProvider(Program.minervaConfig["ContentPath"]);
app.UseStaticFiles(sfo);
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
【问题讨论】:
-
如果您在调用
app.UseStaticFiles(sfo)之后调用app.UseCors("CorsPolicy")会怎样? -
我刚刚测试过:如果 CORS 紧随其后,那么所有静态文件都没有得到 CORS 标头。
-
请看我的回复...静态文件可以使用相同的 CORS 策略 stackoverflow.com/a/55538788/3568316 进行保护
标签: c# asp.net .net asp.net-core asp.net-core-mvc