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?