WCF REST Svc GET返回HTML

时间:2013-05-16 16:20:34

标签: wcf wcf-rest

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

1 个答案:

答案 0 :(得分:11)

当您返回string,结果类型为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 - 这意味着您可以控制输出(有关详细信息,请参阅this blog post),您的代码将类似于下面的代码。这种方法的优点是您的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]

相关问题