ASP.NET Core provides the status code pages middleware, that supports several different extension methods, but we are interesting in UseStatusCodePages
and UseStatusCodePagesWithRedirects
:
UseStatusCodePages adds a StatusCodePages middleware with the given options that checks for responses with status codes between 400 and 599 that do not have a body. Example of use for redirect:
app.UseStatusCodePages(async context => {
//context.HttpContext.Response.StatusCode contains the status code
// your redirect logic
});
UseStatusCodePagesWithRedirects adds a StatusCodePages middleware to the pipeline. Specifies that responses should be handled by redirecting with the given location URL template. This may include a '{0}' placeholder for the status code. URLs starting with '~' will have PathBase prepended, where any other URL will be used as is. For example the following will redirect to ~/errors/<error_code> (for example ~/errors/403 for 403 error):
app.UseStatusCodePagesWithRedirects("~/errors/{0}");