我一定是在做错事但我无法弄明白;从我能说的来看,它似乎是一个CORS问题。我需要将Access-Control-Expose-Headers: *
暴露给任何来源,但是dotnet核心2.1没有按照我的预期行事。
相关的Startup.cs代码:
public void ConfigureServices(IServiceCollection services)
{
//Mapping settings to POCO and registering with container
var settings = new AppSettings.ReportStorageAccountSettings();
Configuration.Bind(nameof(AppSettings.ReportStorageAccountSettings), settings);
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials();
});
});
services.AddSingleton(settings);
services.AddApiVersioning();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("AllowAll");
app.UseHttpsRedirection();
app.UseMvc();
}
此应用程序托管在Azure中,我已在Azure中的CORS设置中添加了*
条目,以便进行更好的衡量。现在,每当客户端应用程序(也在Azure中托管)发出请求时,都无法通过JS访问标头,并且响应中不存在Access-Control-Expose-Headers: *
。但是,当我检查网络响应和使用Fiddler时,我可以看到标题。我已经尝试过Axios和Jquery来访问标题以排除JS的任何问题。我在这做错了什么?
在控制器中,我回复:
Response.Headers.Add("Location", $"api/someLocation");
return StatusCode(StatusCodes.Status202Accepted);
当您在AllowAnyHeader
上使用CorsPolicyBuilder
时,您将设置Access-Control-Allow-Headers
标头,该标头仅用于preflighted requests。为了设置Access-Control-Expose-Headers
,你需要使用WithExposedHeaders
。这是一个完整的例子:
services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()
.WithExposedHeaders("Location"); // params string[]
});
});