如何在WCF中为[WebGet]方法发出裸XML?

Dou*_*eny 10 .net wcf xml-serialization

如何定义[OperationContract] [WebGet]方法来返回存储在字符串中的XML,而不对字符串进行HTML编码?

该应用程序使用WCF服务返回已存储为字符串的XML/XHTML内容.XML与[DataContract]的任何特定类都不对应.它意味着由XSLT使用.

[OperationContract]
[WebGet]
public XmlContent GetContent()
{
   return new XmlContent("<p>given content</p>");
}
Run Code Online (Sandbox Code Playgroud)

我有这门课:

[XmlRoot]
public class XmlContent : IXmlSerializable
{
    public XmlContent(string content)
    {
        this.Content = content;
    }
    public string Content { get; set; }

    #region IXmlSerializable Members

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        throw new NotImplementedException();
    }

    public void WriteXml(XmlWriter writer)
    {

        writer.WriteRaw(this.Content);
    }
    #endregion
}
Run Code Online (Sandbox Code Playgroud)

但是在序列化时,会有一个包含给定内容的根标记.

<XmlContent>
  <p>given content</p>
</XmlContent>
Run Code Online (Sandbox Code Playgroud)

我知道如何更改根标签的名称([XmlRoot(ElementName ="div")]),但我需要省略根标签,如果可能的话.

我也试过[DataContract]而不是IXmlSerializable,但似乎不太灵活.

Che*_*eso 8

返回一个XmlElement.您不需要IXmlSerializable.您不需要包装类.

示例服务接口:

namespace Cheeso.Samples.Webservices._2009Jun01
{
    [ServiceContract(Namespace="urn:Cheeso.Samples.Webservices" )]
    public interface IWebGetService
    {
        [OperationContract]
        [WebGet(
                BodyStyle = WebMessageBodyStyle.Bare,
                    RequestFormat = WebMessageFormat.Xml,
                    ResponseFormat = WebMessageFormat.Xml,
                    UriTemplate = "/Greet/{greeting}")]
        XmlElement Greet(String greeting);
    }
}
Run Code Online (Sandbox Code Playgroud)

服务实施:

namespace Cheeso.Samples.Webservices._2009Jun01
{
    [ServiceBehavior(Name="WcfWebGetService",
                     Namespace="urn:Cheeso.Samples.WebServices",
                     IncludeExceptionDetailInFaults=true)]

    public class WcfWebGetService : IWebGetService
    {
        public XmlElement Greet (String greeting)
        {
            string rawXml = "<p>Stuff here</p>";
            XmlDocument doc = new XmlDocument();
            doc.Load(new System.IO.StringReader(rawXml));
            return doc.DocumentElement;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另请参阅这个类似的问题,但没有WebGet扭曲:
serializing-generic-xml-data-across-wcf-web-service-requests.