S1r*_*lot 6 c# cors asp.net-core asp.net-core-2.1
我一定是在做错事但我无法弄明白; 从我能说的来看,它似乎是一个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();
}
Run Code Online (Sandbox Code Playgroud)
此应用程序托管在Azure中,我在Azure中添加了一个*CORS设置条目,以便更好地衡量.现在,每当客户端应用程序(也在Azure中托管)发出请求时,标头都无法通过JS访问,并且Access-Control-Expose-Headers: *不会出现在响应中.但是,当我检查网络响应和使用Fiddler时,我可以看到标题.我已经尝试过Axios和Jquery来访问标题以排除JS的任何问题.我在这做错了什么?
在控制器中,我回复:
Response.Headers.Add("Location", $"api/someLocation");
return StatusCode(StatusCodes.Status202Accepted);
Run Code Online (Sandbox Code Playgroud)
Kir*_*kin 20
当您使用AllowAnyHeader时CorsPolicyBuilder,您正在设置Access-Control-Allow-Headers标题,该标题仅用于预检请求.要设置Access-Control-Expose-Headers,您需要使用WithExposedHeaders.这是一个完整的例子:
services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()
.WithExposedHeaders("Location"); // params string[]
});
});
Run Code Online (Sandbox Code Playgroud)
正如柯克所说,.WithExposedHeaders()我们需要的是方法。柯克的答案的另一个变体是:
// in Startup.cs
// at the end of ConfigureServices() add:
services.AddCors();
// at the top of Configure() add:
app.UseCors(x =>
x.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("*"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2164 次 |
| 最近记录: |