C# – ASP.Net Response.Close issue

asp.netciis-7netvisual-studio-2008

I am using ASP.Net + .Net 3.5 + VSTS 2008 + IIS 7.0 + C# to develop a web application. I find when debugging in VSTS 2008, if I call Response.Close() method in page_load (please refer to code below), there will be error (from IE when accessing the page) like can not connect to server.

My question is,

  1. Normally when should we call Response.Close()? Or no need to call (rely on ASP.Net framework to automatically close)?

BTW: my previous understanding is developer should always call Response.Close when processing is completed at server side and all data has been written to client using Response.Write. Am I correct?

2 Why I met with such error in my code? What is the root cause?

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Hello World! ");
        Response.Close();
    }

Best Answer

The following from the MSDN website might be useful here:

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.