Rendering 404 Not Found page for ASP.NET Core MVC

I am using the middleware below to set up error pages for HTTP status codes 400 through 599. So the visit /error/400

shows the 400 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, when visiting /this-page-does-not-exist

, a generic IIS 404 Not Found error page appears.

Is there a way to handle requests that don't match any routes? How can I handle this type of request before IIS gets busy? Ideally I would like to redirect the request to /error/404

so that my error controller can handle it.

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

<?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>

      

+4


source to share


1 answer


Based on this SO element , IIS gets 404 (and therefore processes it) before reaching UseStatusCodePagesWithReExecute

.

Have you tried this: https://github.com/aspnet/Diagnostics/issues/144 ? It suggests to terminate the request that received the 404, so it doesn't go to IIS for processing. And here is the code to add to your Startup for that:



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

      

This looks like a problem with IIS.

+3


source







All Articles