Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a 404 Not Found Page for ASP.NET Core MVC

I am using the middle-ware below to set up error pages for HTTP status codes 400 to 599. So visiting /error/400 shows a 400 Bad Request error page.

application.UseStatusCodePagesWithReExecute("/error/{0}");  [Route("[controller]")] public class ErrorController : Controller {     [HttpGet("{statusCode}")]     public IActionResult Error(int statusCode)     {         this.Response.StatusCode = statusCode;         return this.View(statusCode);     } } 

However, visiting /this-page-does-not-exist results in a generic IIS 404 Not Found error page.

Is there a way to handle requests that do not match any routes? How can I handle this type of request before IIS takes over? Ideally I would like to forward the request to /error/404 so that my error controller can handle it.

In ASP.NET 4.6 MVC 5, we had to use the httpErrors section in the Web.config file to do this.

<?xml version="1.0" encoding="utf-8"?> <configuration>   <system.webServer>     <httpErrors errorMode="Custom" existingResponse="Replace">       <remove statusCode="404" />       <error statusCode="404" responseMode="ExecuteURL" path="/error/404/" />     </httpErrors>   </system.webServer> </configuration> 
like image 312
Muhammad Rehan Saeed Avatar asked Jul 24 '15 09:07

Muhammad Rehan Saeed


People also ask

How do I fix HTTP Status 404 not found?

If the URL for a page has changed, the old URL should be retained as a redirect file. Redirects are the easiest way to fix a 404 error. Restore deleted webpages as long as there is no business reason to keep it deleted. If there is a reason to keep it deleted, then the link should be redirected.

How can create custom error page in asp net core?

Serve error pages in ASP.NET Core application. Starting from an empty project, created in a previous post, amend the Configure() method of Startup class to use middleware needed for error handling. Below I've used a custom middleware (defined as lambda) to handle production exceptions, public void Configure(

How do I trigger a 404 error?

The typical trigger for an error 404 message is when website content has been removed or moved to another URL. There are also other reasons why an error message could appear. These include: The URL or its content (such as files or images) was either deleted or moved (without adjusting any internal links accordingly)


2 Answers

One of the best tutorials I found is this: https://joonasw.net/view/custom-error-pages

The summary is here:

1. First add a controller like ErrorController then add this action to it:

[Route("404")] public IActionResult PageNotFound() {     string originalPath = "unknown";     if (HttpContext.Items.ContainsKey("originalPath"))     {         originalPath = HttpContext.Items["originalPath"] as string;     }     return View(); } 

Note: You can add the action to another existing controller like HomeController.

2. Now add the PageNotFound.cshtml view. Something like this:

@{     ViewBag.Title = "404"; }  <h1>404 - Page not found</h1>  <p>Oops, better check that URL.</p> 

3. And the important part is here. Add this code to Startup class, inside Configure method:

app.Use(async (ctx, next) => {     await next();      if(ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)     {         //Re-execute the request so the user gets the error page         string originalPath = ctx.Request.Path.Value;         ctx.Items["originalPath"] = originalPath;         ctx.Request.Path = "/error/404";         await next();     } }); 

Note that it must be added before routing configs like app.UseEndpoints....

like image 127
Mahdi Ataollahi Avatar answered Sep 22 '22 01:09

Mahdi Ataollahi


Based on this SO item, IIS gets the 404 (and therefore handles it) before it reaches UseStatusCodePagesWithReExecute.

Have you tried this: https://github.com/aspnet/Diagnostics/issues/144? It suggests terminating the request that received a 404 so it does not go to IIS to handle. And here's the code to add to your Startup to do so:

app.Run(context => {    context.Response.StatusCode = 404;    return Task.FromResult(0); }); 

This appears to be an IIS-only issue.

like image 39
Frank Fajardo Avatar answered Sep 24 '22 01:09

Frank Fajardo