MiP
MiP

Reputation: 6432

Return NotFound() or unhandled exception with a 404 page

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.

Upvotes: 1

Views: 1830

Answers (1)

Alex
Alex

Reputation: 38509

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

Upvotes: 2

Related Questions