2011-10-26 80 views
3

我構建了一個WCF Rest服務來爲另一個進程提供數據。假設他的名字是GetData。 這一個提供具有該結構的XML響應:定義WCF XML響應模式

<?xml version="1.0" encoding="utf-8"?> 
<GetDataResponse xmlns="http://tempuri.org/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <GetDataResult> 
    <DataMessage> 
     <a></a> 
     <b></b> 
     <c></c> 
    </DataMessage> 
    </GetDataResult> 
</GetDataResponse> 

服務接口:

[XmlSerializerFormat] 
    [OperationContract(Name = "GetData")] 
    [WebInvoke(Method = "GET", 
       ResponseFormat = WebMessageFormat.Xml, 
       BodyStyle = WebMessageBodyStyle.Wrapped, 
       UriTemplate = "Data/{Param}")] 
    List<DataMessage> GetData(string Params); 

我想保存它,繼DataMessage類後反序列化XML。所以,我想有這樣的模式:

<?xml version="1.0" encoding="utf-8"?> 
<DataMessages xmlns="http://tempuri.org/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <DataMessage> 
     <a></a> 
     <b></b> 
     <c></c> 
    </DataMessage> 
</DataMessages> 

我應該怎麼做來定義服務響應模式有它這樣的嗎?

謝謝。

回答

6

您可以使用System.Xml.Serialization名稱空間中的某些屬性來定義映射到您擁有的模式的對象圖。下面的代碼是這樣做的。

public class StackOverflow_7905186 
{ 
    [XmlType(TypeName = "DataMessage", Namespace = "http://tempuri.org/")] 
    public class DataMessage 
    { 
     public string a; 
     public string b; 
     public string c; 
    } 
    [XmlRoot(ElementName = "DataMessages", Namespace = "http://tempuri.org/")] 
    public class DataMessages 
    { 
     [XmlElement(ElementName = "DataMessage")] 
     public List<DataMessage> Messages; 
    } 
    [ServiceContract] 
    public class Service 
    { 
     [XmlSerializerFormat] 
     [OperationContract(Name = "GetData")] 
     [WebGet(ResponseFormat = WebMessageFormat.Xml, 
       BodyStyle = WebMessageBodyStyle.Bare, 
       UriTemplate = "Data/{Param}")] 
     [return: MessageParameter(Name = "DataMessages")] 
     public DataMessages GetData(string Param) 
     { 
      return new DataMessages 
      { 
       Messages = new List<DataMessage> 
       { 
        new DataMessage 
        { 
         a = "1", 
         b = "2", 
         c = "3", 
        } 
       } 
      }; 
     } 
    } 
    public static void Test() 
    { 
     string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; 
     WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress)); 
     host.Open(); 
     Console.WriteLine("Host opened"); 

     WebClient c = new WebClient(); 
     Console.WriteLine(c.DownloadString(baseAddress + "/Data/foo")); 

     Console.Write("Press ENTER to close the host"); 
     Console.ReadLine(); 
     host.Close(); 
    } 
}