Burt
Burt

Reputation: 7758

Passing a complex object as a parameter to a JSON WCF method

I have the following method and the filters parameter is a 2d array of key value pairs. After a bit of research a Post method seems to make more sense, how would I go about rewriting the method to be a post?

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

Upvotes: 0

Views: 2333

Answers (2)

Rajesh
Rajesh

Reputation: 7876

In order to change your above method to post it would look like something below:

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

Your requestBody for the above method might look as shown below (You can inspect using Fiddler):

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

NOTE:

  1. Assuming your key,value pair to be int,string

  2. When you have a POST method, query strings are not supported.

  3. Also rename your method that make it valid as per REST principals where method names indicate a resource on the server which performs a task. GetAll method with WebInvoke attribute is not a good practise.

  4. The default method for WebInvoke is "POST" hence i am not specifying it explicitly.

Upvotes: 2

Rob Rodi
Rob Rodi

Reputation: 3494

To make it a post, you need to change the WebGet to WebInvoke with Method of POST. To use the body of the quest to pass variables, you simply need to add a Serializable object to the parameters list. So, if you have a Dictionary<string,string>, change your method to be

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

Upvotes: 1

Related Questions