将复杂对象作为参数传递给JSON WCF方法

时间:2012-04-10 13:23:42

标签: .net wcf wcf-rest

我有以下方法,filters参数是键值对的2d数组。经过一些研究后,Post方法似乎更有意义,我将如何重写该方法成为一个帖子?

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

2 个答案:

答案 0 :(得分:2)

为了将上述方法更改为发布,它将如下所示:

[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”,因此我没有明确指定它。

答案 1 :(得分:1)

要将其设为帖子,您需要将WebGet更改为WebInvoke Method POST。要使用任务主体传递变量,只需将Serializable对象添加到参数列表即可。因此,如果您有Dictionary<string,string>,请将您的方法更改为

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