404s: Return A “Page Not Found”

I recently came across a situation where we wanted to return a 404 to the client manually. The page requested exists, however it is simply page that accepts a query string parameter which translates this into a filepath and returns the file back to the client via a stream. In the event that the query string parameter did not equate to a valid filepath, for whatever reason (maybe the file has been deleted, or maybe the user has manually typed the query string) we wanted to return a simple 404.

Surprisingly, I had never actually needed to do this before, so this is what I found to be the best way to do this.

Response.Clear();
Response.StatusCode = 404
HttpContext.Current.ApplicationInstance.CompleteRequest();

Quite simply, this will clear all response content and return the 404 status back to the client.

Note that wr have used the CompleteRequest() method instead of Response.End(). This is intentional as it is a better way to handle the closing of a client connection over HTTP.

Response.End()

This forces the HTTP request to come to an end with immediate effect. It does this by raising the ThreadAbortException, which is the frameworks’ was of aborting the current connection. You will most likely see these errors appearing in your error log (such as Elmah), if you use one while using Response.End() in your application.

HttpContext.Current.ApplicationInstance.CompleteRequest()

This is a much cleaner method that allows the applications life-cycle to come to an end more naturally, albeit expedited. In fact what this does is tells the application to skip the rest of the HTTP pipeline chain and go to the EndRequest() event of the application.

One very important thing to note here, however, is that although this will skip to EndRequest(), it does not abort the execution of the life-cycle on the current page, meaning the page will complete execution and then no further processing will occur.

For a download page, such as what we needed this code for, this is fine as the page will then naturally complete as there is no more code to be executed anyway,butnding the 404 back to the client at the end.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s