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
StreamReaderhas a constructor overload that takes a Boolean value as a final parameter namedleaveOpen. Passing intruewill prevent theStreamReaderfrom disposing the underlyingStreamwhen it is itself disposed.Be sure to set the
...Body.Positionproperty 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).