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

.NET6 Razor Pages部署Azure后POST请求体丢失问题排查

.NET 6 Razor Pages部署Azure后POST请求体丢失问题

问题背景

基于.NET 6的Razor Pages应用在本地运行完全正常,但部署到Azure Web App后出现POST请求体丢失的情况。更换多个不同的Azure Web App资源部署,问题依然存在。

出现问题的中间件代码

public async Task Invoke(HttpContext context)
{
    _logger.LogInformation("BodyLogger");
    if (!context.Request.Body.CanSeek)
    {
        context.Request.EnableBuffering();
    }
    if (context.Request.Method == "POST")
    {
        _logger.LogInformation("POST cl=" + context.Request.ContentLength.ToString());
        try
        {
            _logger.LogInformation("BodyLogger try");
            string body = "";
            context.Request.Body.Position = 0;
            using (var reader = new StreamReader(context.Request.Body, leaveOpen: true))
            {
                _logger.LogInformation("BodyLogger using");
                body = await reader.ReadToEndAsync();
            }
            context.Request.Body.Position = 0;

            _logger.LogInformation($"BODY ok (length {body?.Length ?? 0})" + (body ?? "(null)"));
        }
        catch (Exception e)
        {
            _logger.LogError("BODY error " + e.Message);
            throw;
        }
    }

    await _next.Invoke(context);
}

日志情况

从Application Insights的日志来看,POST请求的ContentLength有数值(例如日志显示POST cl=11),但最终读取到的body内容长度为0。

可正常工作的测试中间件

以下中间件无论作为第一个还是最后一个注册,都能正常读取到POST请求体:

app.Use(async (HttpContext context, RequestDelegate next) =>
{
    if (context.Request.Path == "/post")
    {
        if (!context.Request.Body.CanSeek)
        {
            context.Request.EnableBuffering();
        }
        //context.Request.Body.Position = 0;
        context.Request.Body.Seek(0, SeekOrigin.Begin);
        string body = "";
        using (var reader = new StreamReader(context.Request.Body, leaveOpen: true))
        {
            body = await reader.ReadToEndAsync();
        }
        //context.Request.Body.Position = 0;
        context.Request.Body.Seek(0, SeekOrigin.Begin);

        await context.Response.WriteAsJsonAsync("The body was: " + body);
        return;
    }
    await next.Invoke(context);
});

额外异常现象

在Azure环境的Application Insights日志中,缺少Kestrel通常会输出的以下日志条目:

Connection id "0HMOAORGGN3ES", Request id "0HMOAORGGN3ES:00000003": started reading request body.
Connection id "0HMOAORGGN3ES", Request id "0HMOAORGGN3ES:00000003": done reading request body.

请问这是什么原因?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:25:33