当我通过 Angular 服务访问它时,无法获取特定标头 (
Content-Disposition
)。 CORS 已启用,并且 Angular HTTPClient 设置为检索所有标头。
启动.cs
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
ConfigureOAuth(app, config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
文件控制器.cs
[Route("file/{idFile}")]
public HttpResponseMessage GetFile(string idFile)
{
string file;
byte[] file;
document = fileService.GetFile(idDFile, out fileName);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(file)
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = nomeFile
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
文件服务.ts
getFile(fileId: number): Observable<Response> {
const url = `${urlBackEnd}/file/${fileId}`;
return this.http.get(url, { observe: 'response', responseType: 'blob' })
.map(res => {;
console.log(res.headers.keys()); // There's no CONTENT-DISPOSITION
saveAs(<Blob>res.body);
return res.body;
})
.catch(e => this.handleErrors(e));
}
这是 header console.log:
[
"content-type",
"cache-control"
]
我错过了什么?我只想获取
Content-Disposition
标题。
在
fileController.cs
文件中,除了设置 Content-Type
和 Content-Disposition
响应标头之外,您还需要设置 Access-Control-Expose-Headers
:
result.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
请注意,虽然 Fetch 规范实际上允许“
*
”作为 Access-Control-Expose-Headers
的值(尽管通过阅读当前规范文本还不是很清楚……)——浏览器尚未符合该规范;因此,您应该显式列出浏览器应向前端 JavaScript 代码公开的所有响应标头名称 - 除了 Cache-Control
、Content-Language
、Content-Type
、Expires
、Last-Modified
和 Pragma
,它们始终是裸露。对于除这六个响应标头和您在 Access-Control-Expose-Headers
标头值中明确列出的响应标头之外的任何响应标头,浏览器会阻止前端代码访问它们。
我通过调整服务器(ASP.NET Core 8)中定义的 CORS 规则来修复此问题,如下所示
var corsPolicy = new CorsPolicyBuilder()
.WithOrigins(builder.Configuration["FrontendUrl"])
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.WithExposedHeaders(HeaderNames.ContentDisposition)
.Build();
builder.Services.AddCors(options => options.AddPolicy("wasm", corsPolicy));
公开“Content-Disposition”时,您也可以在客户端中阅读它。
httpServletResponse.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
httpServletResponse.setHeader(Content-Disposition,getFileName());
这个解决方案对我有用。