3

我在 WCF 中整理了一个简单的 REST 服务,如下所示:

....
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, UriTemplate = "{uid}/{pwd}/{exrcsPrgmId}/{exchEnum}")]
string GetLiftDataExchange(string uid, string pwd, string exrcsPrgmId, string exchEnum);
....

但是,当调用它时,我并没有准确地返回 XML。我得到了 HTXML(我自己编的首字母缩写词)

而不是我所期望的:

<Exercise>
  <AccountName>Joe Muscle</AccountName>
  <UserID>8008008</UserID>

我得到了带有 html 编码的 XML:

&lt;Exercise&gt;&#xD;
  &lt;AccountName&gt;John Bonner&lt;/AccountName&gt;&#xD;
  &lt;UserID&gt;8008008&lt;/UserID&gt;&#xD;

换句话说,我不需要在浏览器中查看这些数据,而是会在应用程序中访问和解析它,因此直接使用 XML 就可以正常工作。

我在返回这个编码的 xml 的服务装饰上做错了什么?

4

1 回答 1

11

当您返回 astring并且结果类型为 XML 时,您将获得编码为能够表示字符串中的所有字符的字符串 - 这会导致 XML 字符被转义。

您的方案有两种选择。如果您想返回“纯”XML(即 XHTML,或恰好是格式良好的 XML 的 HTML),您可以使用返回类型为XmlElementXElement。这告诉 WCF 您确实想要返回任意 XML。如果您喜欢下面的代码,您将获得所需的“纯”XML。

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "...")]
public XElement GetLiftDataExchange(string uid, string pwd, string exrcsPrgmId, string exchEnum)
{
    return XElement.Parse(@"<Exercise>
            <AccountName>Joe Muscle</AccountName>
            <UserID>8008008</UserID>
        </Exercise>");
}

另一种选择是返回Stream- 这意味着您可以控制输出(有关更多详细信息,请参阅此博客文章),您的代码将类似于下面的代码。这种方法的优点是您的 HTML 不需要是格式良好的 XML(即,您可以有类似<br><hr>有效的 HTML 但不是有效的 XML)。

[OperationContract]
[WebGet(UriTemplate = "...")]
public Stream GetLiftDataExchange(string uid, string pwd, string exrcsPrgmId, string exchEnum)
{
    var str = @"<html><head><title>This is my page</title></head>
            <body><h1>Exercise</h1><ul>
            <li><b>AccountName</b>: Joe Muscle</li>
            <li><b>UserID</b>: 8008008</li></body></html>";
    WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
    return new MemoryStream(Encoding.UTF8.GetBytes(str));
}

在相关节点上,请不要使用[WebInvoke(Method="GET")][WebGet]而是使用。

于 2013-05-16T16:40:04.227 回答