0

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

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
rikush
  • 520
  • 1
  • 6
  • 20
  • Rather than reading the `Body` you can read the `InputStream`. Please check [this answer](https://stackoverflow.com/a/31644235/13268855). – Peter Csala Aug 30 '21 at 08:59
  • the object ActionExecutingContext dont contain InputStream ActionExecutingContext.HttpContext.Request.InputStream get the error: HttpRequest' does not contain a definition for 'InputStream' and no accessible extension method 'InputStream' @Peter Csala – rikush Aug 30 '21 at 09:50
  • `HttpContext`'s type is [HttpContextBase](https://learn.microsoft.com/en-us/dotnet/api/system.web.httpcontextbase). Its `Request`'s type is [HttpRequestBase](https://learn.microsoft.com/en-us/dotnet/api/system.web.httpcontextbase.request). This class does have an [InputStream](https://learn.microsoft.com/en-us/dotnet/api/system.web.httprequestbase.inputstream) property. They are defined in the `System.Web` whereas the `ActionExecutingContext` is defined inside the `System.Web.Mvc`. – Peter Csala Aug 30 '21 at 09:56
  • As I mentioned I am in an ActionFilterAttribute class where I have an ActionExecutingContext object that contains HttpRequest under using Microsoft.AspNetCore.Http @PeterCsala – rikush Aug 31 '21 at 09:53
  • Sorry, [you are right](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.httprequest.body?view=aspnetcore-5.0), my bad. – Peter Csala Aug 31 '21 at 10:29

1 Answers1

0

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).

Moho
  • 15,457
  • 1
  • 30
  • 31