2011-03-27 45 views
2

如何獲取HTTP POST請求中的數據,該數據在我的WCF服務中收到?提取HTTP POST數據(WCF C#)

我使用HTTP POST從其他服務發送的數據:

 string ReportText = "Hello world"; 

     ASCIIEncoding encoding = new ASCIIEncoding(); 
     byte[] data = encoding.GetBytes(ReportText); 

     // Prepare web request... 
     String serverURL = ConfigurationManager.AppSettings["REPORT"]; 
     HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serverURL); 
     myRequest.Method = "POST"; 
     myRequest.ContentType = "application/x-www-form-urlencoded"; 
     myRequest.ContentLength = data.Length; 
     Stream newStream = myRequest.GetRequestStream(); 

     // Send the data. 
     newStream.Write(data, 0, data.Length); 
     newStream.Close(); 

,但是當我在WCF收到POST請求使用WebOperationContext.Current.IncomingRequest, 我不能找到一種方法來提取它我如何從HTTP POST請求中提取數據?

+0

什麼是你爲了支持'應用/在你的WCF服務的X WWW的形式urlencoded'使用綁定? – 2011-03-27 09:03:51

+0

你可以發佈你的服務代碼的樣子嗎?它看起來並不像你連接到WCF,而只是做一個標準的HTTP請求。 – Tridus 2011-03-27 11:43:49

+0

@tridus - 發送POST請求的客戶端將其作爲標準HTTP POST發送,而不是從WCF發送。我如何從我的WCF中提取發送像上面的示例一樣的POST數據? (鏈接,代碼示例...) – Rodniko 2011-03-29 14:55:47

回答

0

Hello world並不完全是application/x-www-form-urlencoded。您需要相應地編碼郵件正文someproperty=Hello%20world以及使用WCF HTTP綁定。

+0

謝謝,你能解釋多一點...你有一個代碼示例?... – Rodniko 2011-03-29 15:00:30

5

我的猜測是,你正在使用WCF REST服務,你可以拉GET參數,但你無法讀取RAW數據後?

如果是這種情況,請在Contract聲明的參數列表末尾添加Stream參數。如果函數末尾有單個流,則框架將其視爲原始數據流。

  [OperationContract] 
      [WebInvoke(Method = "POST", UriTemplate = "DoSomething?siteId={siteId}&configTarget={configTarget}", 
      RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] 
      bool DoSomething(string itemid, Stream body); 


    public bool DoSomething(int siteId, string configTarget, Stream postData) 
    { 
     string data = new StreamReader(postData).ReadToEnd(); 
     return data.Length > 0; 
    } 

請參閱此鏈接瞭解詳情: http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx

+0

謝謝詹姆斯,你的文章幫助我解決了我的問題。我正在嘗試創建Rest WCF服務,它將以內容類型'application/x-www-form-urlencoded'和數據在請求正文中發佈爲'key = value&key = value .....'。爲了讓我的應用程序與第三方服務集成(這將使用所有這些規範調用我的服務),我一直在努力爭取這個結構。 – Shaggy 2017-03-16 12:21:31