You need to enable JavaScript to run this app. .NET Core 3.1的ResultFilterAttribute中读取请求Body始终为空如何解决
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 3.1的ResultFilterAttribute中读取请求Body始终为空如何解决

问题根源

你遇到的两个核心问题原因如下:

  1. 开启请求缓冲的中间件注册顺序错误:如果EnableBuffering的中间件放在了UseRouting、UseAuthorization等会提前读取请求体的中间件之后,缓冲不会生效,请求体流仍然是只进不可回溯的,自然会抛出NotSupportedException
  2. 同步读取请求体+流被意外关闭:在OnResultExecuted阶段请求上下文资源已经开始回收,且用StreamReader默认读取完成后会自动关闭源流,加上阻塞式调用.Result容易引发死锁,也会导致读取结果为空

解决方案

第一步:修正缓冲中间件的注册顺序

将开启请求缓冲的中间件放在Startup.Configure方法的最顶部,确保所有后续中间件读取请求体时缓冲已经生效:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 第一行就注册缓冲中间件,优先级最高
    app.Use(async (context, next) => {
        context.Request.EnableBuffering();
        await next();
    });

    // 后面再放其他原有中间件:UseHttpsRedirection、UseRouting、UseAuthorization、UseEndpoints等
    // ... 其余配置保持不变
}

第二步:重写ResultFilter的请求体读取逻辑

不要使用同步的OnResultExecuted方法,改为重写异步的OnResultExecutionAsync,同时配置StreamReader不关闭源流,代码如下:

public class LogFailureResponseFilter : ResultFilterAttribute
{
    private readonly ILogger<LogFailureResponseFilter> _logger;

    public LogFailureResponseFilter(ILogger<LogFailureResponseFilter> logger)
    {
        _logger = logger;
    }

    public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        // 先执行接口逻辑拿到返回结果
        var resultContext = await next();

        var statusCode = resultContext.HttpContext.Response.StatusCode;
        if (statusCode >= 400)
        {
            // 重置请求体流位置到开头
            resultContext.HttpContext.Request.Body.Position = 0;
            // 配置StreamReader不关闭源流,避免影响后续逻辑
            using var reader = new StreamReader(
                resultContext.HttpContext.Request.Body,
                encoding: Encoding.UTF8,
                detectEncodingFromByteOrderMarks: false,
                bufferSize: 1024,
                leaveOpen: true);
            var body = await reader.ReadToEndAsync();
            // 读完再次重置流位置,不影响其他可能的流操作
            resultContext.HttpContext.Request.Body.Position = 0;

            _logger.LogWarning("Request failed for route path {Path} with status code {StatusCode}. The payload was {Payload}",
                resultContext.HttpContext.Request.Path, statusCode, body);
        }
    }
}

第三步:确认Filter正确注册

如果是全局生效的日志,在Startup.ConfigureServices中注册全局过滤器:

services.AddControllers(options =>
{
    options.Filters.Add<LogFailureResponseFilter>();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 09:12:03