2012-06-27 52 views
1

原因。 Web服務託管在不同域上的其他計算機上,但客戶端和服務器連接到同一網絡。如果我使用UploadString,最重要的是一切正常。C#UploadStringAsync不工作

感謝

回答

1

在調用UploadStringAsync之後,您的程序正在退出,因此它沒有時間獲取響應。在下面的代碼中,如果我在Main方法的末尾刪除Thread.Sleep調用,它將不會打印任何內容。嘗試在退出程序之前等待響應到達。

public class StackOverflow_11218045 
{ 
    [ServiceContract] 
    public interface ITest 
    { 
     [OperationContract] 
     string Echo(string text); 
    } 
    public class Service : ITest 
    { 
     public string Echo(string text) 
     { 
      return text; 
     } 
    } 
    public static void Main() 
    { 
     string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; 
     ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); 
     host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), ""); 
     host.Open(); 
     Console.WriteLine("Host opened"); 

     string data = @"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/""> 
          <s:Header/> 
          <s:Body> 
           <Echo xmlns=""http://tempuri.org/""> 
            <text>Hello</text> 
           </Echo> 
          </s:Body> 
         </s:Envelope>"; 
     var client = new WebClient(); 
     client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted); 
     client.Headers[HttpRequestHeader.ContentType] = "text/xml; charset=utf-8"; 
     client.Headers.Add("SOAPAction", "http://tempuri.org/ITest/Echo"); 

     ManualResetEvent evt = new ManualResetEvent(false); 
     client.UploadStringAsync(new Uri(baseAddress), "POST", data, evt); 
     evt.WaitOne(); 
    } 

    static void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) 
    { 
     Console.WriteLine(e.Result); 
     ((ManualResetEvent)e.UserState).Set(); 
    } 
} 
+0

「睡眠」調用只是爲了表明您沒有得到響應,因爲程序在到達之前退出。一個更好的解決方案(我編輯我的代碼)應該是在發生之前不會退出(例如,使用如上所示的事件)。 – carlosfigueira

+0

感謝您的澄清。 – VVV

2

而不是試圖獲得異步方法的工作,你可以嘗試使用非異步方法,但讓它異步使用工作Task Parallel Library

var client = new WebClient(); 
var data = File.ReadAllText("request.xml"); 
client.Headers.Add("Content-Type", "text/xml;charset=utf-8"); 
client.Headers.Add("SOAPAction", "some string"); 

Task.Factory.StartNew(() => 
{ 
    string returnVal = client.UploadString(new Uri("http://differentdomain/wcf/Service.svc"), data); 
    Console.WriteLine(returnVal); 
}); 

這是一個總體較好策略,因爲它適用於所有長時間運行的操作,而不僅僅是那些具有Async方法和事件處理程序的操作。

它也應該使任何發生的通信/傳輸錯誤更容易發生。

+0

感謝您的新方法。 – VVV