1

I am using custom middleware to log error and warning messages in a dotnet core application. I am able to read the status code but am stuck at reading the http response message. Below is the code :

Code from Controller which returns a bad request :

return BadRequest(errorModel);

Middleware code to log errors :

 public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);

            // Log Bad Request 
            // log anything outside this
            if (context.Response.StatusCode != StatusCodes.Status200OK &&
                context.Response.StatusCode != StatusCodes.Status201Created 
             &&
                context.Response.StatusCode != StatusCodes.Status202Accepted
                )
            {
                var reponseBodyStream = new MemoryStream();
                var originalResponseBody = context.Response.Body;
                await originalResponseBody.CopyToAsync(reponseBodyStream);
                reponseBodyStream.Seek(0, SeekOrigin.Begin);
                var requestBodyText = new 
                StreamReader(reponseBodyStream).ReadToEnd();
            }
        }

The response body is null here. It is not readable as well. Error is obtained at the point where i am copying response stream into other stream.What is wrong with this code and how to read the response message?

SunilA
  • 513
  • 8
  • 19
  • 2
    First you read `context.Response.Body` to a variable called `originalRequestBody`? That sounds like that's wrong. – juunas May 17 '17 at 14:15
  • @juunas : Have edited the code. The basic point is i need to read the response text. – SunilA May 17 '17 at 14:42
  • 1
    Possible duplicate of [How to read ASP.NET Core Response.Body?](http://stackoverflow.com/questions/43403941/how-to-read-asp-net-core-response-body) – Set May 17 '17 at 15:27

0 Answers0