FileStreamResult响应头丢失问题排查求助
问题分析与解决方案
核心问题
接口返回FileStreamResult时,缺失Content-Type、Content-Disposition等关键响应头,且Content-Length显示为0,但实际MemoryStream包含有效数据。
原因定位
问题根源是**MemoryStream的读取指针停留在流末尾**。当从服务获取到流后,指针未重置到起始位置,导致FileStreamResult读取不到任何数据,进而触发异常响应头。
解决方法
1. 重置流位置指针
在返回结果前,将MemoryStream的Position设为0,确保从流的起始处读取数据:
[HttpGet("GetImproveIdeaAttachment")] public async Task<IActionResult> GetImproveIdeaAttachment(string FileName) { DownLoadContainer d = await _streamFileDownloadService.DownLoadFile(ImageStorageType.ImprovementIdeaAttachment, FileName); // 重置流到起始位置 d.DownLoadStream.Position = 0; return new FileStreamResult(d.DownLoadStream, d.MimeType) { FileDownloadName = d.FileName }; }
2. 替代方案:使用FileContentResult
若重置流位置后仍有问题,可将MemoryStream转换为字节数组,通过FileContentResult返回,彻底规避流位置问题:
[HttpGet("GetImproveIdeaAttachment")] public async Task<IActionResult> GetImproveIdeaAttachment(string FileName) { DownLoadContainer d = await _streamFileDownloadService.DownLoadFile(ImageStorageType.ImprovementIdeaAttachment, FileName); byte[] fileBytes = ((MemoryStream)d.DownLoadStream).ToArray(); return File(fileBytes, d.MimeType, d.FileName); }
3. 前置校验流有效性
调试时可添加校验,确认服务返回的流不为空:
// 调试用:校验流长度 if (d.DownLoadStream.Length == 0) { return BadRequest("文件流为空"); }
修复后预期响应头
调整后应能看到完整的响应头,示例如下:
content-length: [实际文件大小]
content-type: application/pdf
content-disposition: attachment; filename="5e7ce5f4-c9fa-428d-8783-a23e8d382fb4.pdf"
date: Tue,25 Oct 2022 21:05:07 GMT
server: Kestrel
内容的提问来源于stack exchange,提问作者Steve Schlichter
相关产品推荐
相关产品推荐

