TecMan TecMan - 7 months ago 45
ASP.NET (C#) Question

Can't return HTTP status 404 for custom error page in ASP.NET

One of our legacy websites based on the classic ASP.NET technology was moved to a new hosting. Now it's a cloud running Windows Azure Pack in which our site is running under .NET Framework 4.6.1.

However, I still can't return a custom error page for a non-existing .aspx resource with the correct HTTP status 404 - the status is always 302. Originally the custom 404 error page was defined like this in web.config:

<customErrors mode="RemoteOnly" defaultRedirect="/error/server-error.aspx">
<error statusCode="404" redirect="/error/resource-not-found.aspx"/>

I did read SO posts like this and tried the suggested answers including setting the redirectMode to ResponseRewrite, but nothing helped or did not work as expected.

Did I miss something, or is there another solution?


I've managed to overcome this problem. First, I turned off redirection for the Error 404 in web.config:

    <customErrors mode="RemoteOnly" defaultRedirect="/error/server-error.aspx">
        <!-- <error statusCode="404" redirect="/error/resource-not-found.aspx"/> -->

Then I added the following Application_Error event handler to my Global.asax:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    Dim serverError As HttpException = DirectCast(Server.GetLastError(), HttpException)

    If Not serverError Is Nothing Then
        If 404 = serverError.GetHttpCode() Then
        End If
    End If
End Sub

Finally, I added the lines below to my Error 404. page (resource-not-found.aspx):

Sub Page_Load()
    ' If you're running under IIS 7 in Integrated mode set,
    ' use this line to override IIS errors:
    Response.TrySkipIisCustomErrors = True

    Response.StatusCode = 404
    Response.StatusDescription = "Page not found"
End Sub

FYI: If you use the MasterPage technology, only the variable part of your MasterPage is redirected. After playing with non-existent resources in various sections of our website, I found this behavior smart and useful for our end users.

ONE MORE THING. To return the HTTP 404 Status code for non-ASPX resources, I use the following setting in my web.config:

    <httpErrors errorMode="Custom" defaultResponseMode="Redirect">
        <remove statusCode="404"/>
        <error statusCode="404" path="/error/resource-not-found.aspx" responseMode="ExecuteURL"/>

Pay attention to the responseMode set to 'ExecuteURL' for the error 404.