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

Asp.Net Core反向代理中StreamContent抛出“响应提前结束”问题排查

Asp.Net Core反向代理中StreamContent引发“响应提前结束”的问题及解决

问题场景

我在Asp.Net Core API中开发反向代理,当使用StreamContent传递请求体时:

if (IsContentMethod(request.Method) && !string.IsNullOrEmpty(requestBody))
{
    requestMessage.Content = new StreamContent(request.Body);
    requestMessage.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(request.ContentType);
}

会抛出**"The response ended prematurely."(响应提前结束)**的异常。但如果先将request.Body读取为字符串:

public static async Task<string> BodyAsStringAsync(this HttpRequest request)
{
    if (request.ContentLength == 0)
    {
        return string.Empty;
    }

    request.Body.Seek(0, SeekOrigin.Begin);
    using var reader = new StreamReader(request.Body, leaveOpen: true);
    return await reader.ReadToEndAsync();
}

再使用StringContent传递,一切正常:

if (IsContentMethod(request.Method) && !string.IsNullOrEmpty(requestBody))
{
    requestMessage.Content = new StringContent(requestBody);
    requestMessage.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(request.ContentType);
}

其余代码完全一致,想知道StreamContent的问题出在哪?

问题原因及解决

后来找到问题根源:出于日志记录需求读取request.Body时,流的位置会被移到末尾,而StreamContent会直接使用流的当前位置,导致HttpClient尝试发送一个已经到末尾的流,最终触发HttpRequestException。

修改后的BodyAsStringAsync方法,在读取完流后将位置重置到起始处,问题解决:

public static async Task<string> BodyAsStringAsync(this HttpRequest request)
{
    if (request.ContentLength == 0)
    {
        return string.Empty;
    }

    request.Body.Seek(0, SeekOrigin.Begin);
    using var reader = new StreamReader(request.Body, leaveOpen: true);
    var result = await reader.ReadToEndAsync();
    request.Body.Seek(0, SeekOrigin.Begin); // 重置流位置
    return result;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 20:55:00