【问题标题】:Empty Response headers received from WebAPI从 WebAPI 收到的空响应标头
【发布时间】:2020-08-15 09:43:53
【问题描述】:

我在前面使用带有 ReactJs 应用程序的 ASP.NET WebApi,我正在创建一个 Get 方法来从服务器下载文件,并且我尝试在响应标头中设置 Content-Type 和 Content-Length :

        var result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StreamContent(new MemoryStream(bytes));
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentLength = bytes.Length;

当我使用如下 fetch 方法从 ReactJs 应用程序调用此方法时:

    await fetch(`someservice/${clientid}/download/${fileName}`, { responseType: "arraybuffer" })
    .then((response) => {
        const reader = response.body.getReader();

        //get total length
        const contentLength = response.headers.get('Content-Length');
        console.log(response.headers);

        //read the data
        let receivedLength = 0; // received that many bytes at the moment
        let chunks = []; // array of received binary chunks (comprises the body)
        while (true) {
            const { done, value } = reader.read();

            if (done) {
                break;
            }
            console.log(value);
            chunks.push(value);
            receivedLength += value.length;

            console.log(`Received ${receivedLength} of ${contentLength}`)
        }

        //concatenate chunks into single Uint8Array
        let chunksAll = new Uint8Array(receivedLength);
        let position = 0;
        for (let chunk of chunks) {
            chunksAll.set(chunk, position);
            position += chunk.length;
        }
    });

我收到了没有 Content-Type 和 Content-Length 标头的响应:

但是 Content-Type 和 Content-Length 不是有效的标头吗?

【问题讨论】:

    标签: javascript reactjs asp.net-web-api http-headers


    【解决方案1】:

    fetch api JavaScript 中的响应标头已实现为迭代器而不是对象,您可以尝试在下面访问标头:-

      for (var header of respone.headers.entries()) {
                        console.log(header);
                    } 
    

    循环中的每个标题项都是一个字符串数组,其中第一个元素是键,第二个元素是值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-25
      • 2014-07-26
      • 1970-01-01
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      相关资源
      最近更新 更多