2011-06-06 31 views
5

我是WCF,REST等的新手。我試圖編寫服務和客戶端。 我想將xml作爲字符串傳遞給服務並獲得一些響應。使用WebInvoke在WCF REST服務體內傳遞XML字符串

我想通過身體的xml到POST方法,但是當我運行我的客戶端時,它只是掛起。

當我將服務更改爲接受參數作爲uri的一部分時,它正常工作。 (當我將UriTemplate從「getString」更改爲「getString/{xmlString}」並傳遞字符串參數時)。

我在粘貼下面的代碼。

服務

[ServiceContract] 
public interface IXMLService 
{ 
    [WebInvoke(Method = "POST", UriTemplate = "getString", BodyStyle=WebMessageBodyStyle.WrappedRequest, 
    RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)] 

    [OperationContract] 
    string GetXml(string xmlstring); 
} 

// Implementaion代碼

public class XMLService : IXMLService 
{ 
    public string GetXml(string xmlstring) 
    { 
     return "got 1"; 
    } 
}  

客戶

string xmlDoc1="<Name>";   
xmlDoc1 = "<FirstName>First</FirstName>"; 
xmlDoc1 += "<LastName>Last</LastName>"; 
xmlDoc1 += "</Name>"; 

HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(@"http://localhost:3518/XMLService/XMLService.svc/getstring"); 
request1.Method = "POST"; 
request1.ContentType = "application/xml"; 
byte[] bytes = Encoding.UTF8.GetBytes(xmlDoc1);   
request1.GetRequestStream().Write(bytes, 0, bytes.Length); 

Stream resp = ((HttpWebResponse)request1.GetResponse()).GetResponseStream(); 
StreamReader rdr = new StreamReader(resp); 
string response = rdr.ReadToEnd(); 

可能有人請指出什麼是錯的呢?

+0

如果您使用'XElement'而不是字符串作爲參數,它會改變嗎?還要設置請求的「Content-Length」。 – 2011-06-06 14:05:36

+0

謝謝你的回覆。 我試過使用XElement。沒有運氣!! – sumi 2011-06-06 14:26:23

回答

8

更改爲使用的XElement和裸

的BodyStyle你的經營合同
[WebInvoke(Method = "POST", 
    UriTemplate = "getString", 
    BodyStyle = WebMessageBodyStyle.Bare, 
    RequestFormat = WebMessageFormat.Xml, 
    ResponseFormat = WebMessageFormat.Xml)] 
[OperationContract] 
string GetXml(XElement xmlstring); 

此外,我懷疑你的客戶端代碼應該包含(注意:第一+ =):

string xmlDoc1="<Name>"; 
xmlDoc1 += "<FirstName>First</FirstName>"; 
xmlDoc1 += "<LastName>Last</LastName>"; 
xmlDoc1 += "</Name>"; 
0

我相信問題是,你設置BodyStyleWrappedRequest這就需要你輸入的XML被包裹在任何命名空間爲您服務合同中定義的<GetXml>元素。如果設置BodyStyleBare和使用XElement作爲@Ladislav Mmka在評論中建議你應該很好去。

0

您需要用合適的Microsoft XML序列化命名空間將您的XML字符串包裝在<string/>標記中。這個問題在此之前已經得到解答,但目前我找不到它。

1

你仍然需要創建一個類:

public class Test 
{ 

    public string xmlstring{ get; set; } 

} 

您還可以使用fiddler來檢查序列化的XM L可以作爲參數傳遞。