从.NET 3.5 WCF Web服务(REST)返回JSON和XML格式

时间:2009-07-16 21:36:08

标签: .net xml wcf web-services json

我有一个返回XML响应的现有Web服务,我想添加一些返回JSON的新方法。我是否必须创建一个以JSON格式返回的单独Web服务,或者我可以混合使用吗?

如果我使用ResponseFormat = WebMessageFormat.JSON,我需要使用[DataContractFormat]注释服务,但我似乎不能使用xml类型响应格式所需的[XmlSerializerFormat]。

3 个答案:

答案 0 :(得分:3)

我不明白为什么这是不可能的。使用[ServiceContract]属性(而不是DataContractFormat)注释服务。它应该看起来像

 [ServiceContract]
    public interface IDoStuff
    {
        [OperationContract]
        [WebInvoke(Method = "POST",
             UriTemplate = "DoStuff",
             ResponseFormat = WebMessageFormat.Json,
             RequestFormat = WebMessageFormat.Json)]
        TestObj DoWork(TestInputObj Inp);
    }

要使其成为xml,只需更改responseformat即可。当您执行post命令时,您将获得json,使用xml格式的单独方法将为您提供xml。

答案 1 :(得分:1)

您是否知道您需要XmlSerializerFormat?只有在需要序列化为不符合数据协定序列化程序规则的XML时才需要这样做。

如果您确实需要,那么您需要第二项服务。这很容易。只需将共同操作的内容提取到单独的方法中,然后从两个服务中调用这些方法。

答案 2 :(得分:0)