skip to Main Content

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


  1. Just make your Error Controller like below for a simple solution

     public class ErrorController : Controller
    {
        // GET: Error
        public ActionResult Index()
        {
            return View("Error");
        }
    }
    

    And use the code below in your web.config file

    <customErrors mode="RemoteOnly" defaultRedirect="Error" />
    
    Login or Signup to reply.
  2. I would use range attributes here. For example given this set of ranges

    What is range?

    • Range It matches an integer within a range of values. {ParameterName:range(1,500)}

    Some known example ranges:

    • Informational responses (100–199)
    • Successful responses (200–299)
    • Redirection messages (300–399)
    • Client error responses (400–499)
    • Server error responses (500–599)

    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.

    public class ErrorController : Controller
    {
        [HttpGet]
        [Route("error/{statusCode:int:range(100,199)}")]
        public ActionResult InformationalResponse(int statusCode)
        {               
            return View();
        }
        [Route("error/{statusCode:int:range(400,499)}")]
        public ActionResult ClientErrorResponse(int statusCode)
        {               
            return View();
        }
    
    }
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search