Brian Hvarregaard
Brian Hvarregaard

Reputation: 4209

ASP.NET and 404 redirect problem

I have a page that reveives a lot of incoming traffic. Some of these fail, and i want to redirect them to my main page to avoid losing potentional customers. I have tried this in my global.asax

void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
            Exception ex = Server.GetLastError();

            if (ex is HttpException)
            {

                if (((HttpException)(ex)).GetHttpCode() == 404)

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

            }

            // Code that runs when an unhandled error occurs

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

        }

And i tried using custom errors, but my application keeps giving me the IIS 7.5 HTTP 404 error page, even though i should have handled it myself.... Everything is working as intended in my development environment, but on my hosted solution is isnt working... any solutions?

Upvotes: 1

Views: 810

Answers (4)

Brian Hvarregaard
Brian Hvarregaard

Reputation: 4209

Solved using a http handler and registering it in web.onfig

Upvotes: 0

Vadim Belyaev
Vadim Belyaev

Reputation: 2859

Try the following:

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

This should redirect user to the custom error page defined in web.config.

Also, it is usually considered as bad practice to redirect user to the main page instead of showing special "Not found" page. User should be aware of the error. Better way is to offer user some useful links on error page as well as quick search form.

Upvotes: 2

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

HTTP 404 is not application error. It is client error which means that requested web resource is not found / doesn't exist. It is returned by web server before it ever reach your application so your error code will never be executed.

Edit: Actually I'm not sure if this didn't change in IIS 7.x integrated mode but for IIS 6 and IIS 7.x in classic mode above statement is true.

Upvotes: 2

Aristos
Aristos

Reputation: 66641

I see in this code a potential dead loop on the same page (default.aspx).

Upvotes: 1

Related Questions