While trying to find the best approach to implementing a catch-all for any uncaught exceptions I found this.
But, while implementing it, I remembered where I read:
WARNING Don't modify the
Response
object after callingnext()
..., as the response may have already started sending and you could cause invalid data to be sent.pg. 580
Is this an issue when the middleware is acting as a global exception handler before the MVC middleware where it seems reasonable that if the exception middleware were invoked, no response could have been started?
Invoke
on Middleware:
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
// A catch-all for uncaught exceptions...
catch (Exception exception)
{
var response = context.Response;
response.ContentType = "application/json";
response.StatusCode = (int)HttpStatusCode.InternalServerError;
await response.WriteAsync(...);
}
}