2015-03-02 59 views
0
[OperationContract] 
[WebInvoke(UriTemplate = "s={s}", Method = "POST")] 
string EchoWithPost(string s); 

我試圖消耗使用WebRequest這個方法(WCF服務):WCF WebInvoke POST郵件正文

WebRequest request1 = WebRequest.Create("http://MyIP/Host"); 
request1.Method = "POST"; 
request1.ContentType = "application/x-www-form-urlencoded"; 
string postData1 = "s=TestString"; 

我不想在URL中傳遞數據(s=TestString)我想要做的是在消息體中傳遞數據。

回答

1

首先,你需要改變你的服務合同是這樣的:

[OperationContract] 
[WebInvoke(UriTemplate = "EchoWithPost", Method = "POST")] 
string EchoWithPost(string s); 

注意的UriTemplate如何不再期待在URL的任何變量的值。

// Set up request 
string postData = @"""Hello World!"""; 
HttpWebRequest request = 
    (HttpWebRequest)WebRequest.Create("http://MyIP/Host/EchoWithPost"); 
request.Method = "POST"; 
request.ContentType = "text/json"; 
byte[] dataBytes = new ASCIIEncoding().GetBytes(postData); 
request.ContentLength = dataBytes.Length; 
using (Stream requestStream = request.GetRequestStream()) 
{ 
    requestStream.Write(dataBytes, 0, dataBytes.Length); 
} 

// Get and parse response 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
string responseString = string.Empty; 
using (var responseStream = new StreamReader(response.GetResponseStream())) 
{ 
    //responseData currently will be in XML format 
    //<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hello World!</string> 
    var responseData = responseStream.ReadToEnd(); 
    responseString = System.Xml.Linq.XDocument.Parse(responseData).Root.Value; 
} 

// display response - Hello World! 
Console.WriteLine(responseString); 
Console.ReadKey(); 

爲了從客戶端調用這樣的操作