WCF Rest Service中的WebGet和非WebGet方法

时间:2011-05-06 05:05:35

标签: wcf rest

以下是我的合同和OperationContracts,我的问题是当我将WebGet属性用于我的服务正常工作的所有方法时,当我将WebGet属性移除到任何一个OperationContracts时,我会收到以下错误。

  

操作'ProductDetails'的   合同'IDemo'指定多个   请求身体参数   序列化没有任何包装   元素。最多一个身体参数   可以在没有包装器的情况下序列化   元素。要么移除额外的身体   参数或设置BodyStyle   物业   WebGetAttribute / WebInvokeAttribute为   缠绕。

这些是我的方法

string AddNumbers(int x,int y);  --- using [WebGet]

string SubtractNumbers(int x, int y); -- using [WebGet]

String ProductDetails(string sName, int cost, int Quntity, string binding); -- not using using [WebGet]

CompositeType GetDataUsingDataContract(CompositeType composite); -- not using [WebGet]

如果我们去WebHttpbinding,是否必须在所有操作合同中包含[WebGet]属性。

public interface IService1
{
    [OperationContract]        
    string GetData(int value,string binding);

    [OperationContract]
    [WebGet(BodyStyle = WebMessageBodyStyle.Bare,
           ResponseFormat = WebMessageFormat.Xml,
           UriTemplate = "/Add?num1={x}&num2={y}")]
    string AddNumbers(int x,int y);

    [OperationContract]
    [WebGet(BodyStyle = WebMessageBodyStyle.Bare,
           ResponseFormat = WebMessageFormat.Xml,
           UriTemplate = "/Subtract?num1={x}&num2={y}")]
    string SubtractNumbers(int x, int y);

    [OperationContract]
    String ProductDetails(string sName, int cost, int Quntity, string binding);

    [OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);
}

1 个答案:

答案 0 :(得分:17)

错误消息确切地说明了问题所在:

  

合同的'ProductDetails'操作   'IDemo'指定多个请求   要序列化的身体参数   没有任何包装元素。 最多   一个身体参数可以序列化   没有包装元素。

您不能拥有期望多个参数的方法,除非您将这些参数包装起来,例如通过在BodyStyle属性中指定WebGet设置。

所以是的:您必须对REST服务的每个方法应用[WebGet],或者您可以重新组织您的方法以仅接受一个参数(例如,通过包含您拥有的两个或三个参数)现在进入一个包含那些多个参数的类,然后传入该Request类的对象实例。)

[DataContract]
public class AddNumbersRequest
{
   [DataMember]
   public int X { get; set; }
   [DataMember]
   public int Y { get; set; }
}   

[OperationContract]
string AddNumbers(AddNumbersRequest request);
相关问题