Sam Heller
Sam Heller

Reputation: 91

Handling 404's better in .NET

As some of you guys are running some pretty big sites I wanted to get your opinion on handling 404’s. I have tried loads of different setups with .Net but can never actually get it to do the right thing. I always seem to get some kind of redirect or false header returned, never a 404. This is a real pain because search engines never get the correct feedback and are still hitting these pages despite them no longer existing. In turn this means I get errors reported for pages I know no longer exist. I’m also pretty confused over the way some requests are handled by .Net and some are handled by IIS.

My current setup is as follows: IIS7, ASP.Net 3.5 App. I have the custom error pages section of web.config setup to handle 404’s using the new redirectMode="ResponseRewrite" property, forwarding to a html error page. IIS is configured to handle 404’s and forward them to the same html page. Elmah is configured to report any such issues via email too.

Now when I try the following address http://www.severnside.com/document.aspx (a page that doesn’t exist), .net handles the error and shows a 200 response. Obviously this should be a 404. When I try http://www.severnside.com/document I get a correct 404 but the error was handled by IIS. Is it possible to have .Net handle this error too so Elmah can pick up the error?

It would be great if I could get an insight into the setups used by others to handle this sort of scenario correctly.

Thanks

Upvotes: 2

Views: 555

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039528

Instead of using static html page you could use dynamic page which will set the correct status code:

404.aspx:

<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
    Response.StatusCode = 404;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Not found
    </div>
    </form>
</body>

web.config:

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm" redirectMode="ResponseRewrite">
  <error statusCode="404" redirect="404.aspx" />
</customErrors>

Upvotes: 8

Related Questions