能够同时响应JSON(P)和XML并仍然用作SOAP web服务的RESTful WCF服务?

时间:2022-04-30 15:22:44

Given a contract such as:

订立合同,例如:

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

Is there a way to get the service to respond with json when requested as: /GetData/1234.json, xml when requested as /GetData/1234.xml and still be available as a proper soap service at some other url, with a strongly typed wsdl contract?

是否有一种方法可以让服务以json形式响应:/GetData/1234。json, xml,请求为/GetData/1234。使用强类型的wsdl契约,仍然可以在其他url作为适当的soap服务使用?

Using a Stream as the return value for GetData is not workable, as though it fufills the first two requirements, wcf can't create a full wsdl specification as it has no idea what the contents of the resultant Stream will be.

使用流作为GetData的返回值是不可行的,因为它模糊了前两个需求,wcf不能创建完整的wsdl规范,因为它不知道生成的流的内容是什么。

1 个解决方案

#1


12  

You should have two separate methods which take id and format (and they would call a shared implementation that returns ResponseData) which have different WebGet attributes:

您应该有两个独立的方法,它们采用id和格式(它们会调用一个返回ResponseData的共享实现),这些方法具有不同的WebGet属性:

[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);
}

For the SOAP endpoint, you should be able to call either method, but you are going to have to have a separate ServiceHost instance hosting the implementation of the contract.

对于SOAP端点,您应该能够调用任何一个方法,但是您必须有一个单独的ServiceHost实例来承载契约的实现。

#1


12  

You should have two separate methods which take id and format (and they would call a shared implementation that returns ResponseData) which have different WebGet attributes:

您应该有两个独立的方法,它们采用id和格式(它们会调用一个返回ResponseData的共享实现),这些方法具有不同的WebGet属性:

[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);
}

For the SOAP endpoint, you should be able to call either method, but you are going to have to have a separate ServiceHost instance hosting the implementation of the contract.

对于SOAP端点,您应该能够调用任何一个方法,但是您必须有一个单独的ServiceHost实例来承载契约的实现。