2010-01-19 38 views

回答

0

我遇到了同樣的問題,我相信有幾種方法可以考慮這樣做。如果還有更多,我很樂意聽取他人的意見。

首先,我會告訴你我是如何做到的。第一步是構建一個實用程序庫,其中包含數據對象結構的類定義,並帶有適當的get方法和構造函數來初始化該對象。此外,還必須使類序列化,即

[Serializable] 
public class myDataObject 
{ 
    private int _n1; 
    private string _s1; 

    public myDataObject(int n, string s) 
    { 
     this._n1 = n; 
     this._s1 = s; 
    } 

    public int getN1() 
    { 
     return this._n1; 
    } 
    public string getS1() 
    { 
     return this._s1; 
    } 
} 

}

把這個庫中,以便您可以從客戶端和服務器端都引用這是很重要的。

一旦你做到了這一點,改變你的WCF服務的方法類似於以下內容:

[WebInvoke(Method = "POST", UriTemplate = "yourDesignedURI")] 
[OperationContract] 
public bool doSomething(myDataObject o) 
{ 
    //implement your service logic, accessing the parameters from o 
    int i = o.getN1(); 
    string s = o.getS1(); 
    //...etc 
    return true; 
} 

一旦完成,發佈您的服務,然後使用幫助頁面從服務查看所需的XML語法。然後,您可以使用Linq to XML來構建XML,從而通過Web將您的數據對象作爲請求發送。這消除了需要來包裝,並公開您的請求XML語法:

<myDataObject xmlns="http://schemas.datacontract.org/2004/07/DemoXMLSerialization"> 
    <_n1>2147483647</_n1> 
    <_s1>String content</_s1> 
</myDataObject> 

參考您的客戶端實用程序庫,然後再創建您的數據的方法來調用服務方法,創造你的方法的元素。

public void callService(int n1, string s1) 
    { 
     myDataObject o = new myDataObject(n1, s1); 
     string serviceURL = "yourBaseURL"; 
     string serviceURI = "yourDesignedURI"; 

     using (HttpClient client = new HttpClient(serviceURL)) 
     { 
      client.DefaultHeaders.Add("Content-Type", "application/xml; charset=utf-8"); 

      XNamespace xns = "http://schemas.datacontract.org/2004/07/DemoXMLSerialization"; 
      XDocument xdoc = new XDocument(
           new XElement(xns + "myDataObject", 
           new XElement(xns + "_n1", o.getN1()) 
           , new XElement(xns + "_s1", o.getS1()))); 
      using (HttpResponseMessage res = client.Post(serviceURI, HttpContent.Create(xdoc.ToString(SaveOptions.DisableFormatting)))) 
      { 
       res.EnsureStatusIsSuccessful(); 
       //do anything else you want to get the response value 
      } 
     } 
    } 

你可以做的另一件事是重新設計你的URI是這樣的: yourdesignedURI/{敏}/{}的myString

,然後使用JSON序列化發送的對象。如果您添加該行

BodyStyle=WebMessageBodyStyle.Bare 

對於您的WebInvoke屬性,幫助頁將公開完整的URI以便於查看。

我相信也可能有一種方法可以用JQuery來實現。希望看到其他解決方案!

希望有所幫助。