Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 6 404 Not Found

Instead of getting a HTTP 404 response, I'd like to have a generic 404 Not Found page (HTTP 200). I know you can set that up in MVC 5 with

<customErrors mode="On">
  <error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>

But I can't seem to figure out how to do this in MVC 6. I'm guessing it should be in either the UseMvc routing table, or a custom middleware.

like image 900
Michael Avatar asked Apr 02 '15 19:04

Michael


2 Answers

If anyone is looking to create custom 404 pages with HTML, you can do this:

Startup.cs

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {        
        app.UseStatusCodePagesWithReExecute("/errors/{0}");
    }
}

project.json

"dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-*",
    // ....
}

ErrorsController.cs

public class ErrorsController : Controller
{
    // ....

    [Route("/Error/{statusCode}")]
    public IActionResult ErrorRoute(string statusCode)
    {
        if (statusCode == "500" | statusCode == "404")
        {
            return View(statusCode);
        }

        return View("~/Views/Errors/Default.cshtml");
    }
}

All that's left after this is to create a 404.cshtml, 500.cshtml, and Default.cshtml in your Errors view folder and customize the HTML to your liking.

like image 195
smulholland2 Avatar answered Oct 01 '22 13:10

smulholland2


Startup.cs:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        // PICK YOUR FLAVOR.

        // app.UseErrorPage(ErrorPageOptions.ShowAll);
        app.UseStatusCodePages(); // There is a default response but any of the following can be used to change the behavior.

        // app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
        // app.UseStatusCodePages("text/plain", "Response, status code: {0}");
        // app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
        // app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
        // app.UseStatusCodePages(builder => builder.UseWelcomePage());
        // app.UseStatusCodePagesWithReExecute("/errors/{0}");
    }
} 

project.json:

"dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-*",
    // ....
}

note that, if you are hosting on IIS (or azure), the web.config does still works and it's big maybe needed in some hosting scenarios. (it should be placed inside wwwroot folder

like image 31
Bart Calixto Avatar answered Oct 01 '22 12:10

Bart Calixto