Reputation: 6246
I'm working with a Web API and trying to receive a dictionary as parameter:
[HttpGet]
public IDictionary<string, string> Get(IDictionary<string,string> myDictionaryAsParameter)
To call it, I'm creating a url querystring with:
string endpoint = "http//localhost:1122/api/MyController/?myDictionaryAsParameter=" + JsonConvert.SerializeObject(parameters)
When debugging the code, the web API method dictionary parameter is Null.
If I change the web API signature to :
[HttpGet]
public IDictionary<string, string> Get(string myDictionaryAsParameter)
{
var dict = JsonConvert.DeserializeObject(myDictionaryAsParameter);
}
It gets parsed correctly.
How should I encode/serialize my dictionary object to send it in url querystring and get it correctly parsed by web API method signature?
Upvotes: 1
Views: 342
Reputation: 18068
If you use:
[HttpGet]
[Route("")]
public IDictionary<string, string> Get(IDictionary<string,string> myParameter)
{
}
Then you'll have to pass myDictionaryAsParameter
via the body and change to [HttpPost]
, since Web API doesn't support a body parameter in HttpGet
.
A few tests I've tried show that only simple parameters are read via URL e.g.
// For URL/value
// I've tried this with complex objects - doesn't work with complex objects
[HttpGet]
[Route("{myParameter}")]
public IDictionary<string, string> Get(string myParameter)
{
}
or:
// For URL?myParameter=value
// Haven't tried this with complex objects - might not work with complex objects
[HttpGet]
[Route("")]
public IDictionary<string, string> Get(string myParameter = "default")
{
}
However, you could try this with the last option (by adding a default value).
Also, the vNext of Web API gives additional routing options, you could try this with VS2015 and the new Web API version.
Upvotes: 1