从针对跨源http.get请求的ASP.NET Web API 2响应中获取Angular中的特定响应标头(例如,Content-Disposition)

时间:2017-12-05 09:33:09

标签: c# angular cors asp.net-web-api2 owin

当我通过Angular服务访问它时,我无法获得特定的标头(Content-Disposition)。启用CORS并将Angular HTTPClient设置为检索所有标头。

Startup.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);
 } 

fileController.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;
        }

fileService.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));
}

这是标题console.log:

[
  "content-type",
  "cache-control"
]

我错过了什么?我只想获得Content-Disposition标题。

2 个答案:

答案 0 :(得分:9)

fileController.cs文件中,设置Content-TypeContent-Disposition响应标头,您需要设置Access-Control-Expose-Headers

result.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

请注意,虽然Fetch规范确实允许&#34; *&#34;作为Access-Control-Expose-Headers的值(尽管通过阅读当前的规范文本并不是很清楚......) - 浏览器还不符合规范;因此,您应该明确列出浏览器应向您的前端JavaScript代码公开的所有响应标头名称 - Cache-ControlContent-LanguageContent-TypeExpires,{{1}除外}和Last-Modified,它们总是被曝光。对于除这六个之外的任何响应头以及您在Pragma头的值中明确列出的那些响应头,浏览器会阻止前端代码访问它们。

答案 1 :(得分:-1)

 httpServletResponse.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
 httpServletResponse.setHeader(Content-Disposition,getFileName());

此解决方案对我有用。