Tom Hamming
Tom Hamming

Reputation: 10991

How to programmatically serve HTTP 404 from ASP.NET code-behind and redirect to 404 page?

I've got an ASP.NET app that sometimes redirects to a 404 page if requested content isn't found. This is done something like this:

var data = MyDatabase.RetrieveData(dataID);
if (data == null)
   Response.Redirect("~/My404Page.aspx");

This works great for users. But it's resulting in 302 Found (a redirect), not 404 Not Found, which is not ideal for search crawlers. I'd like to return a 404 status code and still display helpful content to the user.

The famous internet's most awkard 404 page does this; if you enter a bad URL in that domain and watch the result with something like Fiddler, you actually get a 404 code back.

I've tried this:

Response.StatusCode = 404;

This sets the 404 code properly, but continues rendering the page. I've also tried this:

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

But this does the same thing it would with any other uncaught exception (redirects via 302 to a server error page).

I've figured out a way to solve this in my app via some custom logic that involves setting the status code myself and writing a javascript redirect to the response. But what I'd like to have is a way to express in code-behind that this request should stop processing and redirect to the 404 error page (which I believe can be specified either in IIS or web.config). Is this possible?

Upvotes: 2

Views: 3658

Answers (2)

Helephant
Helephant

Reputation: 17028

You need to do a Server.Transfer rather than a Repsonse.Redirect if you don't want the 302 redirect. Response.Redirect() sends a response back to the browser that tells it to load up your ~/My404Page.aspx. Server.Transfer() transfers control over to your ~/My404Page.aspx without going back to the browser, which means that your browser won't get the 302 redirect message.

You also need to make sure that you set the Response.StatusCode property to 404 on your 404 page.

Alternatively, if you throw the HttpException, you can redirect to your custom 404 page without doing a 302 in the server by setting the redirectMode property to ResponseRewrite. This will only work in newer versions of ASP.NET.

Upvotes: 2

Alex
Alex

Reputation: 35407

Use the CustomErrors attribute in your web applications' web.config:

<configuration>
  <system.web>
    <customErrors defaultRedirect="GenericError.htm"
                  mode="RemoteOnly">
      <error statusCode="404"
             redirect="My404Page.aspx"/>
    </customErrors>
  </system.web>
</configuration>

Upvotes: 1

Related Questions