user710502
user710502

Reputation: 11471

404 Custom Redirect

Hello I am trying to do a redirect if the response is a 404 but it is not working as expected, can you experts see the issue?. It still goes to the generic 404

in my Global.asax

protected void Application_BeginRequest(Object sender, EventArgs e)
{
       if (Response.Status == "404 Not Found")
        {
            string notFound = "~/custom_notfound.aspx";
            Response.Redirect(notFound);
        } 

}

UPDATE

Tried so far

(Response.Status == "404 Not Found")
(Response.Status == "404")
(Response.StatusCode == 404)

Upvotes: 5

Views: 6250

Answers (4)

user3298484
user3298484

Reputation: 1

You can also use the web.config

<system.webServer>
  <httpErrors errorMode="Custom" defaultResponseMode="File" >
     <remove statusCode="404" />
     <remove statusCode="500" />
     <error statusCode="404" path="404.html" />
     <error statusCode="500" path="500.html" />
   </httpErrors>
</system.webServer>

Upvotes: 0

SHug
SHug

Reputation: 688

You can also use the web.config customerrors section - as shown here

e.g. In the system.web section,

<customErrors mode="On" defaultRedirect="/custom_error.aspx">
    <error statusCode="404" redirect="/custom_notfound.aspx" />
</customErrors>

Upvotes: 8

Lou Franco
Lou Franco

Reputation: 89162

I don't think BeginRequest could know about 404 errors. Try implementing Application_Error instead. Check to see if Server.GetLastError() is an HttpException, and if so, check the status.

Upvotes: 3

davisoa
davisoa

Reputation: 5439

You could add to your web.config to do this redirection, you don't need to use Application_BeginRequest to handle this.

See this ServerFault question.

If you can't use the web.config then I would set your startup page to one that doesn't exist, put a breakpoint in your BeginRequest, debug the app and look at the request to see how to determine it is a 404. That would be much easier to determine the optimal solution.

Looking into this some more, there is a HttpStatusCode that is used in the HttpWebResponse class. So it may make sense to use a different override of the Application to get the default response, and then check it's status against the Enum.

Upvotes: 2

Related Questions