I have Asp.Net.Core app in which there have to be some logging, today I tried to add exception handling middleware. I've used UseExceptionHandler which is from asp.net Diagonstics. The problem was that when my logging middleware was after ExceptionHandler middleware
app.UseExceptionHandler("/error");
app.UseSerilogMiddleware();
It wasnot redirectig me to my custom Error page when there was some exception.
public async Task Invoke(HttpContext httpContext)
{
if (httpContext == null)
{
Log.Write(LogEventLevel.Fatal, "No HTTP context found!");
}
HttpRequest request = httpContext.Request;
var logger = GetExtendedLogger(request);
var stopwatchStart = Stopwatch.GetTimestamp();
try
{
var originalResponseBody = httpContext.Response.Body;
using (MemoryStream stream = new MemoryStream())
{
**httpContext.Response.Body = stream;**
await _next(httpContext);
stream.Seek(0, SeekOrigin.Begin);
var responseBody = new StreamReader(stream).ReadToEnd();
var elapsedMs = GetElapsedMilliseconds(stopwatchStart, Stopwatch.GetTimestamp());
var statusCode = httpContext.Response?.StatusCode;
var level = GetLogEventLevel(statusCode);
var log = Log
.ForContext("RequestHeaders", httpContext.Request.Headers.ToDictionary(h => h.Key, h => h.Value.ToString()), destructureObjects: true)
.ForContext("RequestHost", httpContext.Request.Host)
.ForContext("RequestProtocol", httpContext.Request.Protocol);
logger.Write(level, MessageTemplate, httpContext.Request.Method, httpContext.Request.Path, statusCode, elapsedMs, responseBody);
stream.Seek(0, SeekOrigin.Begin);
await stream.CopyToAsync(originalResponseBody);
}
}
// Never caught, because LogException() returns false.
catch (Exception ex) when (AddExceptionLogEntry(logger, httpContext, GetElapsedMilliseconds(stopwatchStart, Stopwatch.GetTimestamp()), ex))
{
}
}'
This is part of the logging middleware, however I found out what was causing the problem but I don't have explanation for it. The problem is in this line httpContext.Response.Body = stream; when I remove seting the responce body to the stream everything works fine.
P.S. The logging method is copy pasted from here