Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have migrated my source code to .net core 3.0. I had a middleware to log request and response of api request.
This middleware used stream (HttpContext.Request.Body and HttpContext.Response.Body) to get json request and response data.

Now I want to replace the stream by PipeReader (HttpContext.Request.BodyReader). I am able to get the request data, but my request body does not validated. I am receiving following error.

"errors": {
"$": [
  "The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."
],


I guess at some point, I have to reset the position of the request body. (I am not sure).

For reference I am uploading the sample project on One drive Sample Project.
Please I need to fix the issue discussed above.
Also please guide me how to log the response data. Should I use the stream as I did in .net core 2.2?

What I have tried:

I tried to Reset the HttpRequest.Body stream to intial position. But get an error, as this is readyonly stream.

I tried to use HttpRequest.EnableBuffering(), but i received exception of disposed object. (HttpRequest.EnbleBuffering() can be used with stream. Therefore it is not valid option).

If i disable to LogRequest() method, then the middleware works fine.
Posted
Updated 18-Dec-19 5:48am

1 solution

By default, the stream will be closed after read, hence threw an exception of disposed object. Hence, got to obtain the BodyReader with leaveOpen flag set to true.

var body = request.BodyReader.AsStream(true);
using var streamReader = new StreamReader(body);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900