簡體   English   中英

Wcf服務將使用SOAP,以及.NET 4.5.1中的Raw Xml和Json

[英]Wcf Service to consume SOAP, plus Raw Xml and Json in .NET 4.5.1

我有一個Wcf服務.NET 4.5.1,可以使用WcfTestClient.exe連接到該服務並發送測試對象,或使用以下方法發送(肥皂)Xml:

<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";
}

這很好。 但是現在,我想通過從Classic 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帖子的網站,將這些數據取反序列化到我的對象中。

我建議您可以打開兩個端點,一個端點用於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"
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM