Home > Software engineering >  ASP.NET MVC Custom Error Page, one page for multiple errors
ASP.NET MVC Custom Error Page, one page for multiple errors

Time:03-22

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***" />

CodePudding user response:

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" />

CodePudding user response:

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/{errorCode:int:range(100,199)}")]
    public ActionResult InformationalResponse(int errorCode)
    {               
        return View();
    }
    [Route("error/{errorCode:int:range(400,499)}")]
    public ActionResult ClientErrorResponse(int errorCode)
    {               
        return View();
    }

}
  • Related