Search code examples
c#asp.net-mvccustom-errors

Why does my 404 redirect not work in my web.config?


In my application I have a custom error for catching all unexpected errors and a 404 for when a user tries to go to a page that does not exist. The issue is, in production I can navigate successfully to an error page either by typing the path to the url in the browser window or by misuse of application but I cannot do the same with the 404. Here is my setup.enter image description here


Solution

  • Error/NotFound will work instead of ~/Error/NotFound and custom errors should be enabled (depending on where you are making requests from):

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

    And also set httpErrors:

    <system.webServer>
        <httpErrors errorMode="Custom" existingResponse="PassThrough">
            <clear />
            <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
        </httpErrors>
    </system.webServer>
    

    Beware that clear will remove static files for all errors. So consider to unlock an set defaultPath of httpErrors.