views:

606

answers:

5

when handling 404 errors in ASP.NET is it ok to set 404 errors to redirect to a page that sends the 404 response code to the browser or should server.transfer be used so the 404 header can be sent to the browser while the url remains the same?

+1  A: 

I would use the customerrors section of the web.config, then you can specify the page you want 404 to go to.

<configuration>
    <system.web>
        <customErrors mode="On" defaultRedirect="Error.aspx">
            <error statusCode="404" redirect="404Error.aspx" />
        </customErrors>
    </system.web>
</configuration>

On the receiving page if you want to still send the 404 you can place this in the page_load event:

Response.Status = "404 Not Found";
Dustin Laine
Still does a 302 temp redirect.
Ted
A: 

My advice is to let the ASP.NET process do the work for you based on your web.config but if you really want to to this in code you should stick with Server.Transfer cause it will save you a postback.

Raphael
+2  A: 

customErrors statusCode="404" results in a 302 temporary redirect then a 404 (if you've set that in your 404 page's code).

Therefore, the following should do it for you in your global.asax or error HttpModule:

    protected void Application_Error(Object sender, EventArgs e)
    {
        Exception exception = Server.GetLastError();
        if (exception is HttpUnhandledException)
        {
            if (exception.InnerException == null)
            {
                Server.Transfer(ERROR_PAGE_LOCATION, false);
                return;
            }
            exception = exception.InnerException;
        }

        if (exception is HttpException)
        {
            if (((HttpException)exception).GetHttpCode() == 404)
            {
                Server.ClearError();
                Server.Transfer(NOT_FOUND_PAGE_LOCATION);
                return;
            }
        }

        if (Context != null && Context.IsCustomErrorEnabled)
            Server.Transfer(ERROR_PAGE_LOCATION, false);
        else
            Log.Error("Unhandled exception trapped in Global.asax", exception);
    }

Edit: Oh, and http://stackoverflow.com/questions/667053/best-way-to-implement-a-404-in-asp-net put me on the road to the imperative Server.ClearError();

See http://www.andornot.com/about/developerblog/2009/10/handling-404-errors-with-aspnet.aspx for a post I did that covers all of this.

Ted
A: 

Response.Redirect will do 302 first than 404 on redirected page. Server.Transfer will keep the URL, so it is 404 on requested page.

I think it all comes down SEO. I suggest using Server.Transfer as it is more clear to browser/search engine that the requested URL is not found. If you use Response.Redirect requested page is 'temporarily' redirected to a not found page. That's not good... 302 is not a good idea.

Brian Kim
A: 

You can also check this article for more details

paxer