Get request body in OnActionExecuting method dotnetCore

765 Views Asked by At

I have web API in .net core3.
In the filter I need to get the request body

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;
}

I get the following error:

Cannot access a disposed object.\r\nObject name: 'FileBufferingReadStream`

any help is appreciated

1

There are 1 best solutions below

0
Moho On

StreamReader has a constructor overload that takes a Boolean value as a final parameter named leaveOpen. Passing in true will prevent the StreamReader from disposing the underlying Stream when it is itself disposed.

Be sure to set the ...Body.Position property to zero when done reading for possible future reads (and perhaps before you read to ensure you are reading from the start of the stream).