【问题标题】:Get request body in OnActionExecuting method dotnetCore在 OnActionExecuting 方法 dotnetCore 中获取请求正文
【发布时间】:2021-10-29 00:21:56
【问题描述】:

我在 .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`

感谢任何帮助

【问题讨论】:

  • 您可以阅读InputStream,而不是阅读Body。请查看this answer
  • 对象 ActionExecutingContext 不包含 InputStream ActionExecutingContext.HttpContext.Request.InputStream 得到错误:HttpRequest'不包含'InputStream'的定义并且没有可访问的扩展方法'InputStream'@Peter Csala
  • HttpContext 的类型是 HttpContextBase。它的Request 的类型是HttpRequestBase。这个类确实有一个InputStream 属性。它们在System.Web 中定义,而ActionExecutingContextSystem.Web.Mvc 中定义。
  • 正如我所提到的,我在一个 ActionFilterAttribute 类中,我有一个 ActionExecutingContext 对象,其中包含使用 Microsoft.AspNetCore.Http @PeterCsala 下的 HttpRequest
  • 对不起,you are right,我的错。

标签: c# .net-core actionfilterattribute


【解决方案1】:

StreamReader 有一个 constructor overload,它将布尔值作为名为 leaveOpen 的最终参数。传入true 将阻止StreamReader 在其自身被释放时释放底层Stream

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 2023-01-19
    • 2015-08-18
    • 1970-01-01
    • 2015-10-15
    • 2016-08-01
    • 2018-08-17
    相关资源
    最近更新 更多