We're using UseStatusCodePagesWithReExecute in combination with a simple custom middleware that sets Response.StatusCode to 500, to successfully to send users to our custom error page on exceptions that occur in mvc controllers.
However, for exceptions that occur in razor/cshtml views, UseStatusCodePagesWithReExecute doesn't send the user to our error page (though our custom middleware does detect these exceptions in Invoke()).
We tried using an Exception Filter as well, but it only traps exceptions from controller actions, not from views.
Is there a way to send users to our error page if the exception originates in a view?
StatusCodePagesMiddleware added by UseStatusCodePagesWithReExecute extension call has the following check after executing of underlying middlewares:
// Do nothing if a response body has already been provided.
if (context.Response.HasStarted
|| context.Response.StatusCode < 400
|| context.Response.StatusCode >= 600
|| context.Response.ContentLength.HasValue
|| !string.IsNullOrEmpty(context.Response.ContentType))
{
return;
}
When rendering of the View starts, MVC middleware fills Response.ContentType with text/html value. That's why above check returns true and request with status code page is not re-executed.
The fix is fair simple. In your middleware that handles exceptions, call Clear() method on Response:
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception)
{
context.Response.Clear();
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
}
Sample Project on GitHub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With