【问题标题】:RESTful WCF service that can respond in both JSON(P) and XML and still be used as SOAP web service?可以在 JSON(P) 和 XML 中响应并且仍然用作 SOAP Web 服务的 RESTful WCF 服务?
【发布时间】:2009-03-03 19:27:28
【问题描述】:

给定一份​​合同,例如:

[ServiceContract] public interface IService
{
    [OperationContract]
    [WebGet(UriTemplate = "GetData/{id}.{format}")]
    ResponseData GetData(string id, string format);
}

有没有办法让服务在请求时以 json 响应: /GetData/1234.json, xml 当被请求为 /GetData/1234.xml 并且仍然可以作为适当的肥皂服务在其他一些 url 上使用,具有强类型的 wsdl 合同?

使用 Stream 作为 GetData 的返回值是不可行的,就好像它满足了前两个要求一样,wcf 无法创建完整的 wsdl 规范,因为它不知道结果 Stream 的内容是什么。

【问题讨论】:

标签: wcf json rest


【解决方案1】:

应该有两个单独的方法,它们采用 id 和 format(它们将调用返回 ResponseData 的共享实现),它们具有不同的 WebGet attributes

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebGet(UriTemplate = "GetData/{id}.{format}.xml", 
        ResponseFormat=WebMessageFormat.Xml)]
    ResponseData GetDataXml(string id, string format);

    [OperationContract]
    [WebGet(UriTemplate = "GetData/{id}.{format}.json", 
        ResponseFormat=WebMessageFormat.Json)]
    ResponseData GetDataJson(string id, string format);
}

对于 SOAP 端点,您应该能够调用任一方法,但您必须有一个单独的 ServiceHost 实例来托管合同的实施。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多