MVC WebApi HttpGet with complex object
asp.net, asp.net-web-api, deserialization, json.net
Solution
Thanks for suggestions, but the only solution that works for me, is the following.
Before:
var data = {
catid: 123,
// <snip>
};
var json = JSON.stringify(data);
$.post('/foo/bar', json, callback);
public class FooController : ApiController
{
[HttpPost, ActionName("bar")]
public void Bar(BarRequest request)
{
// use request.Category to process request
}
}
After:
var data = {
catid: 123,
// <snip>
};
var json = JSON.stringify(data);
$.get('/foo/bar?data=' + encodeURIComponent(json), callback);
public class FooController : ApiController
{
[HttpGet, ActionName("bar")]
public void Bar(string data)
{
var request = JsonConvert.DeserializeObject<BarRequest>(data);
// use request.Category to process request
}
}
This way I don't need to touch any model, validator, etc. on the client or server. Additionally every other solution required me to change the naming conventions on either the server or the client side.
Problem
I have an existing WebApi action, that I want to switch from HttpPost to HttpGet. It currently takes a single complex object as parameter. The model: ``` public class BarRequest { [JsonProperty("catid")] public int CategoryId { get; set; } } ``` The controller: ``` public class FooController : ApiController { //[HttpPost] [HttpGet] [ActionName("bar")] public void Bar([FromUri] BarRequest request) { if (request != null) { // CategoryId should be 123, not 0 Debug.WriteLine("Category ID :: {0}", request.CategoryId); } } } ``` Now when I send the following request, everything works as expected. ``` GET /foo/bar?CategoryId=123 ``` Also the old POST request worked as expected. ``` POST /foo/bar {"catid":123} ``` But now I need the following request to work: ``` GET /foo/bar?catid=123 ``` How can I accomplish this?