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

5
  • Rather than reading the Body you can read the InputStream. Please check this answer. Commented Aug 30, 2021 at 8: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 Commented Aug 30, 2021 at 9:50
  • HttpContext's type is HttpContextBase. Its Request's type is HttpRequestBase. This class does have an InputStream property. They are defined in the System.Web whereas the ActionExecutingContext is defined inside the System.Web.Mvc. Commented Aug 30, 2021 at 9: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 Commented Aug 31, 2021 at 9:53
  • Sorry, you are right, my bad. Commented Aug 31, 2021 at 10:29

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.