从跨域 http.get 请求的 ASP.NET Web API 2 响应中获取 Angular 中的特定响应标头(例如,Content-Disposition) [英] Get a specific response header (e.g., Content-Disposition) in Angular from an ASP.NET Web API 2 response for a cross-origin http.get request

查看:26
本文介绍了从跨域 http.get 请求的 ASP.NET Web API 2 响应中获取 Angular 中的特定响应标头(例如,Content-Disposition)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过 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}")]公共 HttpResponseMessage GetFile(string idFile){字符串文件;字节[]文件;document = fileService.GetFile(idDFile, out fileName);var 结果 = 新的 HttpResponseMessage(HttpStatusCode.OK){内容 = 新字节数组内容(文件)};result.Content.Headers.ContentDisposition =new System.Net.Http.Headers.ContentDispositionHeaderValue("附件"){文件名 = 名称文件};result.Content.Headers.ContentType =new MediaTypeHeaderValue("application/octet-stream");返回结果;}

fileService.ts

getFile(fileId: number): Observable{const url = `${urlBackEnd}/file/${fileId}`;返回 this.http.get(url, { 观察: 'response', responseType: 'blob' }).map(res => {;console.log(res.headers.keys());//没有内容处理saveAs(res.body);返回 res.body;}).catch(e => this.handleErrors(e));}

这是标题 console.log:

<预><代码>[内容类型",缓存控制"]

我错过了什么?我只想获取 Content-Disposition 标头.

解决方案

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

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

请注意,虽然 Fetch 规范实际上允许*"作为 Access-Control-Expose-Headers 的值(尽管从阅读当前规范文本...) — 浏览器尚不符合规范;因此,您应该明确列出浏览器应向前端 JavaScript 代码公开的所有响应标头名称——除了 Cache-ControlContent-LanguageContent-TypeExpiresLast-ModifiedPragma,它们总是公开的.对于除这六个和您在 Access-Control-Expose-Headers 标头的值中明确列出的响应标头之外的任何响应标头,浏览器都会阻止前端代码访问它们.

I cannot get a specific header (Content-Disposition) when I'm accessing it via an Angular service. CORS is enabled and the Angular HTTPClient is set to retrieve ALL headers.

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

Here's the header console.log:

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

What am I missing? I just want to get the Content-Disposition header.

解决方案

In the fileController.cs file, along with setting the Content-Type and Content-Disposition response headers, you need to set Access-Control-Expose-Headers:

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

Note that while the Fetch spec does actually allow "*" as the value of Access-Control-Expose-Headers (though that’s not very clear from reading the current spec text…) — browsers don’t yet conform to the spec on that; so instead you should explicitly list all response header names the browser should expose to your frontend JavaScript code — except for Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, and Pragma, which are always exposed. For any response headers other than those six and the ones you explicitly list in the value of the Access-Control-Expose-Headers header, browsers block frontend code from accessing them.

这篇关于从跨域 http.get 请求的 ASP.NET Web API 2 响应中获取 Angular 中的特定响应标头(例如,Content-Disposition)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆