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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With