HttpWebRequest myHttpWebRequest1=(HttpWebRequest) WebRequest.Create("http://www.contoso.com/codesnippets/next.asp");
// Create an instance of the RequestState and assign 'myHttpWebRequest1' to it's request field.    
RequestState myRequestState = new RequestState();
myRequestState.request = myHttpWebRequest1;
// Set the ContentType property. 
myHttpWebRequest1.ContentType="application/x-www-form-urlencoded";
// Set the 'Method' property to 'POST' to post data to the Uri.
myHttpWebRequest1.Method="POST";
myHttpWebRequest1.ContentType="application/x-www-form-urlencoded";
// Start the Asynchronous  'BeginGetRequeststream' method call.    
IAsyncResult result=(IAsyncResult) myHttpWebRequest1.BeginGetRequestStream(new AsyncCallback(ReadCallback),myRequestState);            
// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest1.GetResponse();
Stream streamResponse=myHttpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuff = new Char[256];
int count = streamRead.Read( readBuff, 0, 256 );
Console.WriteLine("\nThe contents of HTML Page are :  ");    
while (count > 0) 
{
    String outputData = new String(readBuff, 0, count);
    Console.Write(outputData);
    count = streamRead.Read(readBuff, 0, 256);
}
// Close Stream object.
streamResponse.Close();
streamRead.Close();
allDone.WaitOne();
// Release the HttpWebResponse Resource.
myHttpWebResponse.Close();
Console.WriteLine("\nPress 'Enter' key to continue.................");    
Console.Read();
        }
        catch(WebException e)
        {
Console.WriteLine("WebException raised!");
Console.WriteLine("\n{0}",e.Message);
Console.WriteLine("\n{0}",e.Status);
        } 
        catch(Exception e)
        {
Console.WriteLine("Exception raised!");
Console.WriteLine("Source : {0}" , e.Source);
Console.WriteLine("Message :{0} " , e.Message);
        }
    }
    private static void ReadCallback(IAsyncResult asynchronousResult)
    {    
        try
        {// Set the State of request to asynchronous.
RequestState myRequestState=(RequestState) asynchronousResult.AsyncState;
HttpWebRequest  myHttpWebRequest2=(HttpWebRequest)myRequestState.request;
// End of the Asynchronus  writing .
Stream postStream=myHttpWebRequest2.EndGetRequestStream(asynchronousResult);
Console.WriteLine("\nPlease enter the input data to be posted to the (http://www.contoso.com/codesnippets/next.asp) Uri:");
String inputData=Console.ReadLine();
string postData="firstone="+inputData;    
ASCIIEncoding encoder = new ASCIIEncoding();
// Convert the string into byte array.
byte[] ByteArray = encoder.GetBytes(postData);
// Write to the stream.
postStream.Write(ByteArray,0,postData.Length);
postStream.Close();
Console.WriteLine("\nThe string entered is successfully posted  to the  Uri ");
Console.WriteLine("Please wait for the response.......");
allDone.Set();    
        }
         catch(WebException e)
        {
Console.WriteLine("WebException raised!");
Console.WriteLine("\nMessage:{0}",e.Message);
Console.WriteLine("\nStatus:{0}",e.Status);
        } 
        catch(Exception e)
        {
Console.WriteLine("Exception raised!");
Console.WriteLine("Source :{0} " , e.Source);
Console.WriteLine("Message :{0} ", e.Message);
        }
    }

解决方案 »

  1.   

    是GET命令而不是POST。这段代码我调试过,不行的。
      

  2.   

    http://chs.gotdotnet.com/quickstart/howto/doc/ASPXNet/GETAsync.aspx
      

  3.   

    异步编程范例
    异步编程的过程与单个应用程序域的过程一样简单: 创建可以接收对方法进行的远程调用的对象实例。 
    用 AsyncDelegate 对象包装该实例方法。 
    用另外一个委托包装该远程方法。 
    在第二个委托上调用 BeginInvoke 方法,并传递所有参数、AsyncDelegate 和某个保持状态的对象(或空引用,在 Visual Basic 中为 Nothing)。 
    等待服务器对象调用您的回调方法。 
    尽管这是常规方法,但可以在一定程度上改变它。如果要在任何时候等待某个特定调用返回,只需要获取从 BeginInvoke 调用返回的 IAsyncResult 接口,检索该对象的 WaitHandle 实例,然后调用 WaitOne 方法,如下面的代码示例所示。[Visual Basic]
    Dim RemoteCallback As New AsyncCallback(AddressOf Me.OurCallBack)
    Dim RemoteDel As New RemoteAsyncDelegate(AddressOf obj.RemoteMethod)
    Dim RemAr As IAsyncResult = RemoteDel.BeginInvoke(RemoteCallback, Nothing)
    RemAr.AsyncWaitHandle.WaitOne()[C#]
    AsyncCallback RemoteCallback = new AsyncCallback(this.OurCallBack);
    RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(obj.RemoteMethod);
    IAsyncResult RemAr = RemoteDel.BeginInvoke(RemoteCallback, null);
    RemAr.AsyncWaitHandle.WaitOne();或者,您可以在检查该调用是否已完成的循环中(或者通过使用 System.Threading 基元,如 ManualResetEvent 类)等待,然后动手结束调用。[Visual Basic]
    Dim RemoteCallback As New AsyncCallback(AddressOf Me.OurCallBack)
    Dim RemoteDel As New RemoteAsyncDelegate(AddressOf obj.RemoteMethod)
    Dim RemAr As IAsyncResult = RemoteDel.BeginInvoke(RemoteCallback, Nothing)
    If RemAr.IsCompleted Then
      Dim del As RemoteAsyncDelegate = CType(CType(RemAr, AsyncResult).AsyncDelegate, RemoteAsyncDelegate)
      Console.WriteLine(("**SUCCESS**: Result of the remote AsyncCallBack: " _
        + del.EndInvoke(RemAr)))
    ' Allow the callback thread to interrupt the primary thread to execute the callback.
    Thread.Sleep(1)
    End If ' Do something.[C#]
    AsyncCallback RemoteCallback = new AsyncCallback(this.OurCallBack);
    RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(obj.RemoteMethod);
    IAsyncResult RemAr = RemoteDel.BeginInvoke(RemoteCallback, null);
    if (RemAr.IsCompleted){
      RemoteAsyncDelegate del = (RemoteAsyncDelegate)((AsyncResult) RemAr).AsyncDelegate;
      Console.WriteLine("**SUCCESS**: Result of the remote AsyncCallBack: "  
        + del.EndInvoke(RemAr) );
    // Allow the callback thread to interrupt the primary thread to execute the callback.
    Thread.Sleep(1);
    }最后,可以使主线程创建 ManualResetEvent 并且等待回调函数,然后,回调函数将在返回前的最后一行向 ManualResetEvent 发出信号。有关此类型等待的示例,请参见远程处理示例:异步远程处理中的源代码注释。
      

  4.   

    为什么我接收过来的Word文档比原文件大200多字节,导致文档无法打开?
    如果是图片就就可以。
    该Word文档是Exchange中附件,我是向Exchange发送请求取附件,是不是Exchange对.net的异步请求不支持。
    该Word文档放在普通站点下,一切正常。
      

  5.   

    有一处不明白,回调函数中
    Stream postStream=myHttpWebRequest2.EndGetRequestStream(asynchronousResult);
    语句结束后,是返回了所有数据,还是只返回一部分数据。
    它的执行机制是怎么样的?
      

  6.   

    问题解决了,利用Webclient类的DownloadData 方法可以轻松的解决该问题。