WCF返回带有转义字符的XML / JSON

时间:2014-10-15 15:43:21

标签: c# xml json wcf wcf-binding

我有一个用2个端点编写的WCF服务:

      <service name="API.MyService" behaviorConfiguration="serviceBehavior">
    <endpoint  address="" binding="webHttpBinding" contract="API.IMyService" bindingConfiguration="webHttpBinding_IMyService" behaviorConfiguration="web">
    </endpoint>
    <endpoint address="soap" binding="basicHttpBinding" contract="API.IMyService" bindingConfiguration="basicHttpBinding_IMyService">
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  </service>

Web服务的要求让我们使用EntityFramework对象的反射来为消费者提供他们从中请求数据的特定表的实时表示。目的是这将允许在返回数据中自动提出对架构的更改,而无需重新编码/重建服务。因此,我们不是返回类对象的集合,而是构建XMLDocument并返回doc.OuterXML或根据请求标头将其转换为JSON。

这是我的ServiceContract界面中的操作:

            [OperationContract]
    [WebInvoke(Method = "GET", 
               UriTemplate = "References?param1={param1}&param2={param2}")]
    string References(string param1, string param2);

当我向ASP.Net项目添加服务引用并使用客户端对象调用操作时:

            API.APIClient apiClient = new API.APIClient();

        using (new OperationContextScope(apiClient.InnerChannel))
        {
            // Add a HTTP Header to an outgoing request
            HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
            requestMessage.Headers["Return-Content"] = "application/json";
            OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
            string references = apiClient.References("param1", "param2");
        }

我的返回数据(无论是XML还是JSON)看起来很棒。

但是 - 当我使用WebClient对象调用URL时,返回的数据,所有字段和值都会被双引号转义。

            WebClient client = new WebClient();
        client.Headers.Add("Content-Type", "application/json");

        string url = "http://localhost:62200/API.svc/References?param1=param1&param2=param2";
        byte[] response = client.DownloadData(url);
        string data = Encoding.UTF8.GetString(response);

从数据剪切:“{\”APIPost \“:{\”@ Operation \“:\”References \“,\”Responses \“:{\”Response \“:{\”@ Type \“: \ “CommitsNoExceptions \”}} \ “信息\”:{\ “铅\”:{\ “字段\”:[{\ “@名称\”:\ “SalutationTypeId \”,\ “@必选\”: \ “假\”},{\ “@名称\” .....

我已经看到SO帖子说要返回一个对象集合并让框架进行序列化,但在这种情况下我不能这样做。我可以使用一些配置设置进行此绑定吗?

提前致谢。

0 个答案:

没有答案