如何在WCF Rest Service中将类对象作为参数传递

时间:2015-02-10 05:38:36

标签: c# query-string wcf-rest

这是我的界面代码

      [OperationContract]
       [WebGet(RequestFormat = WebMessageFormat.Json,
         ResponseFormat = WebMessageFormat.Json,
          BodyStyle = WebMessageBodyStyle.Bare,
          UriTemplate = "/Insert?customer={customer}")]
       void InsertDetailsData(CustomerClass customer);

我的班级方法就像

      public void InsertDetailsData(CustomerClass cust)
      {
        SqlConnection scon = new SqlConnection(myConnection);
        scon.Open();
        cust.CustomerName = "adsd";
        cust.Address = "asdasd";
        cust.FirstName = "asd";
        cust.LastName = "asda";
        string query = "Insert into TblCustomer(CustomerName,FirstName,LastName,Address)";
        query += " values('" + cust.CustomerName + "','" + cust.FirstName + "','" + cust.LastName + "','" + cust.Address + "')";

        SqlCommand cmd = new SqlCommand(query, scon);
        cmd.ExecuteNonQuery();
        scon.Close();

    }

但是我收到了像

这样的错误
  

操作' InsertDetailsData'在合同' ICustomerService'有一个名为' customer'的查询变量类型' CustomerService.CustomerClass',但键入' CustomerService.CustomerClass'由QueryStringConverter'不能兑换。 UriTemplate查询值的变量必须具有可由' QueryStringConverter转换的类型。

尝试了

  public class MyQueryStringConverter : QueryStringConverter
    {
        public override bool CanConvert(Type type)
        {
            return (type == typeof(CustomerClass)) || base.CanConvert(type);
        }
        public override object ConvertStringToValue(string parameter, Type parameterType)
        {
            if (parameterType == typeof(CustomerClass))
            {
                string[] parts = parameter.Split(',');
                return new CustomerClass { FirstName = parts[0], CustomerName = parts[1], LastName = parts[2], Address = parts[3] };
            }
            else
            {
                return base.ConvertStringToValue(parameter, parameterType);
            }
        }
    }
    public class MyWebHttpBehavior : WebHttpBehavior
    {
        protected override QueryStringConverter GetQueryStringConverter(OperationDescription operationDescription)
        {
            return new MyQueryStringConverter();
        }
    }

我仍面临同样的错误。

1 个答案:

答案 0 :(得分:0)

此请求仅发送简单类型,uritemplates在方法中生成映射的参数。

[WebGet(UriTemplate = "Method/{Par1}/{par2}")]

如果要传递类必须使用POST方法WebInvoke。

  

这个msdn描述

https://msdn.microsoft.com/tr-tr/library/system.servicemodel.web.webinvokeattribute%28v=vs.110%29.aspx