首页 > 解决方案 > 在 OnActionExecuting 方法 dotnetCore 中获取请求正文

问题描述

我在 .net core3 中有 Web API。
在过滤器中,我需要获取请求正文

public override void OnActionExecuting(ActionExecutingContext context)
{
    string body = ReadBodyAsString(context.HttpContext.Request);
}

private string ReadBodyAsString(HttpRequest request)
{
    var initialBody = request.Body; // Workaround

    try
    {
        request.EnableBuffering();

        using (StreamReader reader = new StreamReader(request.Body))
        {
            string text = reader.ReadToEnd();
            return text;
        }
    }
    finally
    {
        // Workaround so MVC action will be able to read body as well
        request.Body = initialBody;
    }

    return string.Empty;
}

我收到以下错误:

无法访问已释放的对象。\r\n对象名称: 'FileBufferingReadStream`

任何帮助表示赞赏

标签: c#.net-coreactionfilterattribute

解决方案


StreamReader有一个构造函数重载,它接受一个布尔值作为名为 的最终参数leaveOpen。传入true将阻止 the在其本身被处置时StreamReader处置底层资产。Stream

确保...Body.Position在完成读取后将属性设置为零以备将来读取(并且可能在您读取之前确保您从流的开头读取)。


推荐阅读