You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 8中FileStreamResult无法发送字节的问题排查

ASP.NET Core 8 FileStreamResult 返回文件时出现 Response Content-Length mismatch 错误的解决方法

错误现象

fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HNCVO92UT954", Request id "0HNCVO92UT954:00000003":
An unhandled exception was thrown by the application.
System.InvalidOperationException: Response Content-Length mismatch: too few bytes written (0 of 22827).

实际客户端接收不到任何字节,断点确认MemoryStream已写入8字节数据。

问题原因

向MemoryStream写入数据后,流的当前位置(Position)会停在数据末尾。ASP.NET Core处理FileStreamResult时,会从流的当前位置开始读取内容,此时从末尾读取自然获取不到任何字节,进而触发内容长度不匹配的错误。

解决方法

方法1:手动重置流的读取位置

在返回FileStreamResult前,将流的Position设置为0,让读取操作从流的起始处开始:

[HttpGet]
[Route("api/{unitControlNumber}/{startDate}/{endDate}")]
public async Task<IActionResult> RecordsExport(Guid? unitControlNumber, DateTime? startDate, DateTime? endDate)
{
    Stream stream = new MemoryStream();
    byte[] thingBytes = {1,2,3,4,5,6,7,8}; 
    stream.Write(thingBytes, 0, thingBytes.Length);

    stream.Flush();
    // 关键:重置流位置到起始点
    stream.Position = 0;

    FileStreamResult file = new FileStreamResult(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    file.FileDownloadName = $"Board_Data_For_Unit-{unitControlNumber}__Start-{startDate}__End-{endDate}";
    file.EnableRangeProcessing = false;

    return file;
}

方法2:直接用字节数组初始化MemoryStream

使用MemoryStream的重载构造函数直接传入字节数组,此时流的默认位置就是起始处,无需手动调整:

byte[] thingBytes = {1,2,3,4,5,6,7,8};
// 直接用字节数组初始化,Position默认在0
Stream stream = new MemoryStream(thingBytes);

补充说明

该错误与ASP.NET Core 8.0.16版本、IIS服务器或Windows 11环境无关,属于流操作的基础问题。对于其他类型的流(如文件流),同样需要确保读取前流的位置处于正确的起始点,避免类似问题。

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 23:03:18