Why not to use HttpResponse.Close and HttpResponse.End
I’ve seen many times developers use HttpResponse.Close and HttpResponse.End when they want to end the request and send a response to the client. If you read the MSDN explanation about HttpResponse.Close Method, in Remarks you will see the following explanation:
This method terminates the connection to the client in an abrupt manner and is not intended for normal HTTP request processing. The method sends a reset packet to the client, which can cause response data that is buffered on the server, the client, or somewhere in between to be dropped.
You might use this method in response to an attack by a malicious HTTP client. However, typically you should call CompleteRequest() instead if you want to jump ahead to the EndRequest event and send a response to the client.
So, as it says, this method terminates the connection to the client in an abrupt manner and is not intended for normal HTTP request processing.
On the other hand, the HttpResponse.End Method, from the first versions of .NET Framework, was provided for compatibility with the COM based Web Programming technology that was predecessor of the ASP.NET (the classic ASP), which in this case is not anymore needed to be used.
So, if you read the MSDN remarks for both HttpResponse.Close and HttpResponse.End methods, you will see that in normal cases, we should replace both with the HttpApplication.CompleteRequest method. This method will directly call the EndRequest event and the request will end.
See the comparison with the following code examples.
Here is one code example where I’ve used Response.End to terminate the current connection to the client.
{
Response.Write("Hello Hajan");
Response.End();
Response.Write("<br />Goodbye Hajan");
}
After calling the Response.End method, no other code line after this will execute. So, if you have any other code that needs to be executed, this will skip executing the code, which might result in a wrong or unexpected behavior.
The result of the above code is
Hello Hajan
If we use the CompleteRequest method, the code will be:
{
Response.Write("Hello Hajan");
this.Context.ApplicationInstance.CompleteRequest();
Response.Write("<br />Goodbye Hajan");
}
This way, we will again end the http request but the code will continue executing till the last line.
The result of the above code is
Hello Hajan
Goodbye Hajan
To sum up things, instead of using the HttpResponse.End and HttpResponse.Close methods, the best would be to use the HttpApplication.CompleteRequest method, so that the response data that is buffered on the server, the client or in between won’t get dropped.
For more readings, please see the reference links.
Regards,
Hajan
References:
Consuming Events - MSDN Article
Response.End, Response.Close, and How Customer Feedback Helps Us Improve MSDN Documentation - ASP.NET and Web Tools Developer Content Team
HttpApplication.EndRequest Event – MSDN Article