Search code examples
c#.nethttpexception

Throw 404 in c# to go to customerror.aspx without 302 and 301


I have custom errors set in web.config for a 404 error and in IIS. My custom error page works ok.

I want to be able to go to my custom error page from a page load event.

If I throw a 404 using

throw new HttpException(404, "Not found");

I get to the custom error page but looking at the responses I get a 302 found and a 301 permanent redirect then a 404 generated.

How can I remove the 302 and 301?

I have tried Response.Clear() before throwing the exception and also Response.StatusCode=404.


Solution

  • By default when there's an HTTP error IIS will redirect with a 302 to the error page. You can tell IIS to instead rewrite the response with the defined error page in the web.config : With the customErrors tag :

    <system.web>
        <customErrors redirectMode="ResponseRewrite">
            <error statusCode="404" redirect="~/Error404.aspx"/>
        </customErrors>
    </system.web>
    

    This works only with aspx pages, not with ASP.NET MVC

    with the httpErrors tag :

    <system.webServer>
        <httpErrors errorMode="Custom" existingResponse="Replace">
            <remove statusCode="404" subStatusCode="-1" />
            <error statusCode="404" path="/Error404.aspx" responseMode="ExecuteURL"/>
        </httpErrors>
    </system.webServer>
    

    With httpErrors you can't use ~/ to reference the root of the application, but it'll work with / if your application is not hosted as a sub application in IIS