C# – IIS overriding custom 404 error page in ASP.NET

asp.netchttp-status-code-404iis-7

I am trying to create a 404 error page and currently I have all of the following/tried all of the following to try and accomplish this. When the user types in :

http://name/something.aspx

It works just as its supposed to. But if the user types in:

http://name/NotAFile

with no .aspx then IIS7 takes matters into its own hands and I get the lovely error page that IIS7 comes with. The goal is that the site redirects with only a 404 status code (so not a 200, or a 302 redirect). I have tried in both the web config with:

<customErrors mode="On" defaultRedirect="~/error/Default.aspx redirectMode="ResponseRewrite">
     <error statusCode="404" redirect="~/error/NotFound.aspx" />
</customErrors>

This works for the url with a .aspx file extension but not for no extension. Same with this approach in the global.asax

void Application_Error(object sender, EventArgs e)
{
    var serverError = Server.GetLastError() as HttpException;

    if (serverError != null)
    {
        if (serverError.GetHttpCode() == 404)
        {
            Server.ClearError();
            Server.Transfer("~/error/NotFound.aspx");
        }

        Server.Transfer("~/error/Default.aspx");
    }
}

The same results are present for this 🙁 My final attempt was to apply this to the web config:

<system.webServer>
    <httpErrors existingResponse="PassThrough" />
</system.webServer>

With this I just get a plain white screen with nothing on it…
Any thoughts or comments would be greatly appreciated!! Thanks in advance!

Best Answer

The following codes works with both .aspx and other file types:

Global.asax

void Application_Error(object sender, EventArgs e)
{
    var serverError = Server.GetLastError() as HttpException;
    if (serverError != null)
    {
        if (serverError.GetHttpCode() == 404)
        {
            Server.ClearError();
            Response.Redirect("~/NotFound.aspx?URL=" + Request.Url.ToString());
        }
        Response.Redirect("~/Default.aspx");
    }
}

Web.config

<system.webServer>
    <httpErrors existingResponse="PassThrough" />
</system.webServer>