【问题标题】:Passing a complex object as a parameter to a JSON WCF method将复杂对象作为参数传递给 JSON WCF 方法
【发布时间】:2012-04-22 19:07:03
【问题描述】:

我有以下方法,过滤器参数是键值对的二维数组。经过一番研究,一个 Post 方法似乎更有意义,我将如何重写该方法以成为一个帖子?

[WebGet(UriTemplate = "/tools/data/getall?tool={tool}&filters={filters}")]
public JsonArray GetAll(string tool, string filters)
{
}

【问题讨论】:

    标签: .net wcf wcf-rest


    【解决方案1】:

    为了改变你上面的发布方法,它看起来像下面这样:

    [WebInvoke(UriTemplate = "/tools/data/SearchAll")]
    public JsonArray SearchAll(string tool, Dictionary<int,string> filters)
    {
    }
    

    上述方法的 requestBody 可能如下所示(您可以使用 Fiddler 进行检查):

    {
    "tool": "enter the value of tool parameter", 
    "filters" : 
     {
      {"Key":1,"Value":"Test"},
      {"Key":2,"Value":"Test1"}
     }
    }
    

    注意:

    1. 假设您的键值对是 int,string

    2. 当您有 POST 方法时,不支持查询字符串。

    3. 还要重命名您的方法,使其根据 REST 主体有效,其中方法名称表示服务器上执行任务的资源。带有 WebInvoke 属性的 GetAll 方法不是一个好习惯。

    4. WebInvoke 的默认方法是“POST”,因此我没有明确指定它。

    【讨论】:

    【解决方案2】:

    要使其成为帖子,您需要将WebGet 更改为WebInvokeMethodPOST。要使用 quest 的主体来传递变量,您只需将 Serializable 对象添加到参数列表中。因此,如果您有 Dictionary&lt;string,string&gt;,请将您的方法更改为

    [WebInvoke(Method = "POST", UriTemplate = "/tools/data/getall?tool={tool}&filters={filters}")]
    public JsonArray GetAll(string tool, string filters, 
                            Dictionary<string,string> whatever)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      相关资源
      最近更新 更多