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.
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.
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.