Search code examples
asp.netiis-7.5

Forcing custom 404 pages for pages in URL Routing


Coding Platform ASP.NET 4.0 WebForms on IIS7.5

If I request a page blahblah.aspx which does not exist, I get navigated to my custom error page for Page not found Exception. I have implemented URL routing and so I have omitted all my .aspx extensions for routes.

Now, If I type www.mysite.com/blahblah (thats a url without extension) instead of going to my custom error page, it gets redirected to my IIS 404 error page.

What should I do to make my custom error page appear on my site instead of IIS error page?


Solution

  • The Easy Way

    If your IIS 7 web server doesn't already have it, install the IIS 7.0 Administration Pack from Microsoft.

    Navigate to the root web server name in IIS, and open the Configuration Editor (part of the Administration Pack). Change the dropdown to system.webServer/httpErrors, right-click on defaultPath, and choose 'defaultPath' Attribute -> Unlock Attribute.

    Unlocking the defaultPath attribute

    Then try to change the custom error handler page again. Navigate to your site, open Error Pages under the IIS group, click Edit Feature Settings on the right, select Custom error pages and finally, put in your path for the default page.

    Setting custom error pages

    No lock error this time.

    I originally tried to unlock this attribute at the web site level but was prevented, so be aware you may have to go all the way to the root of the IIS tree, the web server itself.

    The Manual Way

    I know you can accomplish all this by direct editing in notepad of the appropriate config file on the web server. And that may be required for your particular web hosting environment or company production web server change protocols. But why make it complicated if it doesn't need to be? Plus, this way you can do it in the GUI, and compare the before and after to see what changes you truly have to make. But if you MUST do it manually, then:

    Open the file %windir%\System32\inetsrv\config\applicationHost.config in Notepad. Run Notepad as administrator if you're having problems.

    Pro tip: Do not use notepad++ to edit applicationHost.config. You'll end up secretly and silently saving a 32-bit copy of the file that's in a different folder than the one IIS looks in (due to Windows, not np++) without actually affecting the file you wish to change.

    You'll see something like this:

    <httpErrors lockAttributes="allowAbsolutePathsWhenDelegated,defaultPath">
    

    Remove the ,defaultPath section and save.

    You will be able to make the changes you need.