MVC 6 404 not found

Instead of receiving an HTTP 404 response, I would like to get a 404 Not Found (HTTP 200) common page. I know you can install this in MVC 5 with

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

But I can’t figure out how to do this in MVC 6. I assume that this should be either in the UseMvc routing table or in regular middleware.

+9
asp.net-mvc asp.net-core asp.net-core-mvc
Apr 02 '15 at 19:42
source share
6 answers

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 host on IIS (or azure), web.config is still working and it is large, it may be necessary in some hosting scripts. (it should be placed in wwwroot folder

+13
Apr 07 '15 at 18:57
source share

You can handle 404 errors using UseStatusCodePagesWithReExecute but you need to set the status code at the end of the configuration pipeline first.

 public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); if (string.Equals(_env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase)) { app.UseDeveloperExceptionPage(); app.UseRuntimeInfoPage(); } else { app.UseExceptionHandler("/Error"); } app.UseStatusCodePagesWithReExecute("/Error/Status/{0}"); app.UseStaticFiles(); app.UseMvc(); app.Use((context, next) => { context.Response.StatusCode = 404; return next(); }); } 

This will set the status code to 404 if nothing in the pipeline can handle it (what you need).

Then you can easily capture and process the response in any way you want in your controller.

 [Route("error")] public class ErrorController : Controller { [Route("Status/{statusCode}")] public IActionResult StatusCode(int statusCode) { //logic to generate status code response return View("Status", model); } } 
+4
Dec 23 '15 at 14:45
source share

If someone wants 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 remains after this is to create 404.cshtml, 500.cshtml and Default.cshtml in your Error Viewer folder and configure the HTML to your liking.

+3
Sep 20 '16 at 0:57
source share

In the Configure function of the Startup class, call:

 app.UseErrorPage(ErrorPageOptions.ShowAll); 

more finished products:

  if (string.Equals(env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase)) { app.UseBrowserLink(); app.UseErrorPage(ErrorPageOptions.ShowAll); app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll); } else { // Add Error handling middleware which catches all application specific errors and // send the request to the following path or controller action. app.UseErrorHandler("/Home/Error"); } 
+1
Apr 7 '15 at 19:45
source share

There is middleware called StatusCodePagesMiddleware that I believe was added after Beta3.

Example: https://github.com/aspnet/Diagnostics/blob/dev/samples/StatusCodePagesSample/Startup.cs

0
Apr 02 '15 at 21:30
source share

If you have a standard ASP.NET 5 web application template project, you can get a really nice solution that will treat as saving the error status code at the same time as maintaining the cshtml file of your choice.

Startup.cs , in the Configure method

Replace

 app.UseExceptionHandler("/Error"); 

from

 app.UseStatusCodePagesWithReExecute("/Home/Errors/{0}"); 

Then remove the following command:

 app.Run(async (context) => { var logger = loggerFactory.CreateLogger("Catchall Endpoint"); logger.LogInformation("No endpoint found for request {path}", context.Request.Path); await context.Response.WriteAsync("No endpoint found - try /api/todo."); }); 

In HomeController.cs

Replace the current Error method as follows:

 public IActionResult Errors(string id) { if (id == "500" | id == "404") { return View($"~/Views/Home/Error/{id}.cshtml"); } return View("~/Views/Shared/Error.cshtml"); } 

This way you can add error files that you think users can get (while search engines still get the correct status codes)

Now add a folder called Error to the ~Views/Home folder. Create two .cshtml files. Name the first 404.cshtml and the second 500.cshtml .

Give them useful content and run the application and write something like http://localhost:44306/idonthaveanendpointhere and confirm that the installation works.

Also click on the F12 developer tools and confirm that the status code is 404.

0
Feb 12 '16 at 14:12
source share



All Articles