2014-02-13 32 views
1

我有一個Wcf服務.NET 4.5.1,我可以使用WcfTestClient.exe連接到併發送測試對象或(soap) Xml喜歡使用以下內容;Wcf服務消費SOAP,再加上原始的Xml和JSON在.NET 4.5.1中

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> 
    <s:Header> 
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IService/PostData</Action> 
    </s:Header> 
    <s:Body> 
    <PostData xmlns="http://tempuri.org/"> 
     <person xmlns:d4p1="PersonNameSpace" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
     <d4p1:Id>1</d4p1:Id> 
     <d4p1:Name>My Name</d4p1:Name> 
     </person> 
    </PostData> 
    </s:Body> 
</s:Envelope> 

我的界面如下;

[ServiceContract] 
public interface IService 
{ 
    [OperationContract] 
    [WebInvoke(Method = "POST", 
     UriTemplate = "PostData", 
     RequestFormat = WebMessageFormat.Xml, 
     BodyStyle = WebMessageBodyStyle.Bare)] 
    string PostData(Person person); 
} 

[DataContract(Namespace = "PersonNameSpace")] 
public class Person 
{ 
    [DataMember] 
    public int Id { get; set; } 

    [DataMember] 
    public string Name { get; set; } 
} 

用我的方法如下;

public string PostData(Person person) 
{ 
    //do something with the object 
    return "Well done"; 
} 

這工作正常。但現在,我想通過從傳統ASP頁面傳遞原始Xml或Json來調用相同的PostData方法;

<PostData> 
    <person> 
     <Id>1</Id>   
     <Name>My name</Name> 
    </person> 
</PostData> 

或JSON格式

{ 
    "PostData": { 
    "person": { 
     "Id": "1", 
     "Name": "My name" 
    } 
    } 
} 

我怎樣才能消耗這些數據作爲XML或JSON,這樣我可以使用XmlSerializer的或類似的東西;

JavaScriptSerializer.Deserialize(PostDataString);

我想要做什麼基本上是該請求是否是使用SOAP一個應用程序,或使用基本的XML職位的網站,藉此數據,並將其Deserialise到我的對象。

回答

2

我建議你可以打開兩個端點,一個用於xml,另一個用於json。這是爲了更好地使用REST時的做法,也更適合客戶使用。

[OperationContract] 
[WebInvoke(Method = "POST", 
    ResponseFormat = WebMessageFormat.Xml, 
    BodyStyle = WebMessageBodyStyle.WrappedRequest, 
    UriTemplate = "/PostDataXML")] 
string PostDataXML(Person person); 

[OperationContract] 
[WebInvoke(Method = "POST", 
    ResponseFormat = WebMessageFormat.Json, 
    BodyStyle = WebMessageBodyStyle.WrappedRequest, 
    UriTemplate = "/PostDataJSON")] 
string PostDataJSON(Person person); 

然後你只需要這個對象發佈到您的服務:

{ 
    "person": { 
    "Id": "1", 
    "Name": "My name" 
    } 
} 
+0

這是我唯一的選擇,因爲我有能力10層的方法,這在總 – Tommassiov

+0

與在20彎了腰你可以仍然將這兩個webinvoke分配給相同的操作合同。兩個端點只是練習,你可以找到更適合你的模型的任何東西。 – HOKBONG

+0

我嘗試了你的建議,但得到「System.Net.WebException:遠程服務器返回錯誤:(404)未找到。」 – Tommassiov