Matt Wilko
Matt Wilko

Reputation: 27322

Handle IIS 404 Error in ASP.NET Code

I am checking for a valid page in my Global.asax file like this:

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
    ' Fires at the beginning of each request

    Dim path As String = HttpContext.Current.Request.Path.ToUpper

    If Not (path.EndsWith(".ASPX") OrElse path.EndsWith(".PNG") OrElse path.EndsWith(".GIF") OrElse path.EndsWith(".MASTER") OrElse path.EndsWith(".JS") OrElse path.EndsWith(".CSS") OrElse path.EndsWith(".PDF")) Then
        'invalid page
        Response.Redirect("/ErrorPageNotFound.aspx?aspxerrorpath=" + HttpContext.Current.Request.Path)

    End If
End Sub

And I have modified by web.config to include the line:

<error statusCode="404" redirect="ErrorPageNotFound.aspx"/>

This works fine when running under Visual Studio Development Server or UltiDev Web Server, but when I use Local IIS Web Server in Visual Studio or full blown IIS and try to get to the nonexistant foo.php I get the standard IIS 404 error page. Note that if I navigate to foo.aspx I get my custom error page.

It seems as if IIS is seeing the request before it gets to my code and deciding to reroute it? Is there any way round this?

Upvotes: 1

Views: 3312

Answers (1)

Peter Hahndorf
Peter Hahndorf

Reputation: 11222

You are just handling 404 errors for asp.net, php, png and all other non-dot-net files are not affected by this.

You need to set 404 pages on the IIS level to handle all invalid requests including ones for asp.net.

for example in your web.config add:

<system.webServer>
  <httpErrors existingResponse="Auto" errorMode="Custom" defaultResponseMode="File">
    <remove statusCode="404" subStatusCode="-1"/>
    <error statusCode="404" path="404.html"/>
  </httpErrors>
</system.webServer>

Upvotes: 3

Related Questions