How to return 'own' 404 custom page? How to return 'own' 404 custom page? asp.net asp.net

How to return 'own' 404 custom page?


<customErrors mode="On" defaultRedirect="~/Error/GenericErrorPage.aspx">     <error statusCode="404" redirect="~/Error/404.aspx" /></customErrors>

http://msdn.microsoft.com/en-us/library/h0hfz6fc(v=vs.71).aspx

http://msdn.microsoft.com/en-us/library/aa479319.aspx


A ha!

Try this:

Response.TrySkipIisCustomErrors = true;Response.Status = "404 Not Found";Response.StatusCode = 404;

I found as soon as I added Response.TrySkipIisCustomErrors=true before setting the status code, I would see the normal page copy AND a 404 is returned. Without this line the standard IIS 404 page is displayed.

Alternatively, this can be set in the web.config like so:

<system.webServer>    <httpErrors existingResponse="PassThrough">        // custom error page mappings    </httpErrors></system.webServer>

The key thing here is existingResponse="PassThrough"

This was added to IIS7 thus is required on sites running in Integrated Pipeline mode.

For more info: http://msdn.microsoft.com/en-us/library/system.web.httpresponse.tryskipiiscustomerrors.aspx

UpdateUpdating for clarrification/more info as people are still finding this useful. It's worth noting that if you need a simple, generic 404 page use the web.config method (and best make it a plain HTML page).

The method I describe works best if you have a heavily dynamic or CMS driven site where any given page could potentially return a 404 but you want to show your visitor related info.

For example, a special offers page (offers/some-offer) could do a lookup for the offer (some-offer) and if it doesn't exist show alternative or related offers while returning a 404 under the bonnet. As far as the visitor is aware they've just been told the offer is no longer available but they're still in the offers section but we're also telling robots to un-index the URL.This would be a lot harder to do if there was just one generic 404 page.


You can achieve this by configuring your web.config file. Please check the link below to an article, which explains at the bottom of the page, how to display different custom error pages for different HTTP error statuses.