如何通过WCF服务网站获取XML响应?

时间:2017-06-20 15:41:22

标签: xml wcf

我需要使用WCF服务网站的XML输出
interface IService class

public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "GET",
    ResponseFormat = WebMessageFormat.Xml,
    BodyStyle = WebMessageBodyStyle.Bare,
    UriTemplate = "GetPay")]
    Payload GetPay();
}
[XmlRoot(ElementName = "payload")]
public class Payload
{
    [XmlElement(ElementName = "firstname")]
    public string Firstname { get; set; }
    [XmlElement(ElementName = "secondname")]
    public string Secondname { get; set; }
    [XmlElement(ElementName = "number")]
    public string Number { get; set; }
}
[XmlRoot(ElementName = "payloads")]
public class Payloads
{
    [XmlElement(ElementName = "payload")]
    public List<Payload> Payload { get; set; }
}

我的服务类位于

之下
public class Service : IService
{
    public Payload GetPay()
    {
        return new Payload(); 
    }
}

我的Web.congig文件代码

<?xml version="1.0"?>
    <configuration>
        <system.web>
              <compilation debug="true" targetFramework="4.0"/>
        </system.web>
        <system.serviceModel>
             <behaviors>
                 <serviceBehaviors>
                     <behavior>
                       <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                        <serviceMetadata httpGetEnabled="true"/>
                        <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                        <serviceDebug includeExceptionDetailInFaults="false"/>
                   </behavior>
               </serviceBehaviors>
           </behaviors>
       <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
   </system.serviceModel>
   <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
   </system.webServer>
</configuration>

我需要以下格式输出。请帮忙

<?xml version="1.0" encoding="UTF-8"?>
<payloads>
    <payload>
        <firstname>Sid</firstname>
        <secondname>Singh</secondname>
        <number>1</number>
    </payload>
    <payload>
        <firstname>Deepak</firstname>
        <secondname>Shahi</secondname>
        <number>2</number>
    </payload>
    <payload>
        <firstname>Shorya</firstname>
        <secondname>Garg</secondname>
        <number>3</number>
    </payload>
</payloads>

请帮助我们找到解决方案。

1 个答案:

答案 0 :(得分:1)

此链接可以帮助您

How to produce XML output using WCF service?

或者请将属性[Serializable()]添加到类Payloads并使用以下代码:

Serialize(listObj)

public static string Serialize(object obj)
{
   var xs = new XmlSerializer(obj.GetType());
   var xml = new StringWriter();
   xs.Serialize(xml, obj);
   return xml.ToString();
}