1

I'm currently using ASP.NET Core, how do I set a 404 default page for unhandled exceptions or NotFound()?

IActionResult Foo()
{
    throw new Exception("Message!");
}

IActionResult Bar()
{
    return NotFound("Message!");
}

I think there is a IApplicationBuilder.UseExceptionHandler method to set an error page, but I don't know how to configure it.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
MiP
  • 5,846
  • 3
  • 26
  • 41

1 Answers1

2

This is explained here under Configuring status code pages

app.UseStatusCodePagesWithRedirects("/error/{0}");

You'll need an ErrorController which could look like:

public class ErrorController : Controller 
{
    public IActionResult Index(string errorCode)
    {
        return View(errorCode);
    }
}

Your views (in the Error folder) would need to be called:

  • 500.cshtml
  • 404.cshtml

...etc

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Alex
  • 37,502
  • 51
  • 204
  • 332
  • After I make these pages, if I `return NotFound("MyError!")` how do I catch the error string? – MiP May 29 '17 at 16:12
  • 1
    Using this method, you can't... It just redirects based on status code – Alex May 29 '17 at 16:13