使用HttpResponseMessage返回gzip时出现ERR_CONTENT_DECODING_FAILED错误
解决ERR_CONTENT_DECODING_FAILED错误的方案
问题核心:你把gzip压缩内容的Base64编码字符串直接通过StringContent返回,同时设置了Content-Encoding: gzip头。浏览器会把返回的文本内容当作gzip原始字节解码,但实际内容是Base64字符串,并非真正的gzip二进制数据,导致解码失败。
修复步骤:
- 将Base64字符串解码为原始的gzip二进制字节数组
- 使用
ByteArrayContent封装二进制数据,替代StringContent(StringContent会把内容当作文本处理,破坏二进制结构) - 保留正确的响应头配置
修复后的代码:
HttpResponseMessage response = Request.CreateResponse(); // 将Base64字符串解码为gzip二进制字节 byte[] gzipBytes = Convert.FromBase64String("H4sIAAAAAAAAAytJLS5RKIETAAP1QQcPAAAA"); response.Content = new ByteArrayContent(gzipBytes); response.StatusCode = HttpStatusCode.OK; response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); response.Content.Headers.ContentType.CharSet = Encoding.UTF8.HeaderName; response.Headers.Add("Vary", "Accept-Encoding"); response.Content.Headers.ContentEncoding.Clear(); response.Content.Headers.ContentEncoding.Add("gzip"); return response;
修复逻辑说明:现在返回的是真正的gzip压缩二进制数据,浏览器收到后能正确解码,同时响应头的Content-Encoding和实际内容格式匹配,最终会正常显示"test test test"。
内容的提问来源于stack exchange,提问作者Mikioe
相关产品推荐
相关产品推荐

