2011-02-10 143 views
1

我已經建立了一個WCF服務,它將以同一方法同時接受JSON和XML,並支持SOAP和REST。WCF REST請求和響應中的XML格式

JSON工作正常,但我不知道XML應該如何顯示。

界面看起來是這樣的:

[ServiceContract] 
public interface IWebService 
{ 
    [OperationContract] 
    [WebInvoke(BodyStyle = WebMessageBodyStyle.Bare)] 
    string[] EchoArray(string[] stringArray); 
} 

如果可能的話,我想保持XML儘可能的簡單,沒有命名空間,就像這樣:

<stringArray> 
    <string>hello</string> 
    <string>hola</string> 
</stringArray> 

的反應應該是簡單以及。

如果它有什麼不同,我會在代碼中完成所有工作,不需要任何web.config。

這是我可以使用Azure輔助角色。

回答

1

我決定去一個包請求而不是裸露的(因爲其他方法所需要的話),並推斷出如何格式化。

首先,我改變了

[ServiceContract] 

[ServiceContract(Namespace = "")] 

那麼這工作:

<EchoArray> 
    <stringArray xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> 
     <a:string>hello</a:string> 
     <a:string>hola</a:string> 
    </stringArray> 
</EchoArray> 

這將沒有包裝的請求可能工作,但爲了保持一致性我做這個方法也包裝好了。

0

如果你想控制的XML是什麼樣子,你可以這樣做:

[ServiceContract] 
public interface IWebService 
{ 
    [OperationContract] 
    [WebInvoke(BodyStyle = WebMessageBodyStyle.Bare)] 
    StringArray EchoArray(StringArray stringArray); 
} 

public class StringArray : IXmlSerializable { 
     public XmlSchema GetSchema() { 
      return null; 
     } 

     public void ReadXml(XmlReader reader) { 
      // However you have formatted it 
     } 

     public void WriteXml(XmlWriter writer) { 
      // However you want it formatted 
     } 
}