I am trying to add custom error page to my web application and I did the following based on some answers on stack overflow,
The Controller
public class ErrorController : Controller
{
public ViewResult Index()
{
return View("Error");
}
public ViewResult NotFound()
{
Response.StatusCode = 404; //you may want to set this to 200
return View("NotFound");
}
}
I have added two views, Error.cshtml and NotFound.cshtml
and I added the following to the web.config file:
<customErrors mode="On" defaultRedirect="~/Error">
<error redirect="~/Error/Error" statusCode="404" />
</customErrors>
I need to have one page for all errors, or for the same error category, for example one page for all 400s errors so instead of doing
<error redirect="~/Error/Error" statusCode="400" />
<error redirect="~/Error/Error" statusCode="401" />
<error redirect="~/Error/Error" statusCode="402" />
do something like
<error redirect="~/Error/Error" statusCode="40***" />
2
Answers
Just make your Error Controller like below for a simple solution
And use the code below in your web.config file
I would use range attributes here. For example given this set of ranges
What is range?
Some known example ranges:
Now, given that I can create a controller with a route attribute and define a range – using the method name to help document what it is about for maintenance purposes: Here are a couple of those, will leave it to you to determine the view etc. here.
Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
New to routing? https://visualstudiomagazine.com/articles/2014/10/28/asp-net-mvc-5-1-new.aspx
Attribute routing: https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0#attribute-routing-for-rest-apis