2017-06-20 41 views
1

我需要的是下面如何通过WCF服务网站获取XML响应?

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> 

我需要使用WCF服务的网站
接口IService

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

我的服务类XML输出以下列格式输出。请帮忙

<?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

此链接可以帮助你

How to produce XML output using WCF service?

否则请添加属性[序列化()类有效载荷,并使用下面的代码:

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(); 
}