seems like I have the most basic problem, yet I cannot find the documentation I need to solve it.
I have an mvc webapi controller:
public class TestController : ApiController
{
[HttpGet]
public MyClass Other([FromUri]MyClass id)
{
id.Value++;
return id;
}
}
public class MyClass
{
public int Value {get;set;}
}
which I am executing from a HttpClient:
using (var client = new System.Net.Http.HttpClient())
{
client.BaseAddress = new System.Uri("http://localhost:31573/api/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var obj = new MyClass { Value = 3 };
var data = JsonConvert.SerializeObject(obj);
StringContent queryString = new StringContent(data, Encoding.UTF8, "application/json");
var paramsValue = queryString.ReadAsStringAsync().Result;
var response = client.GetAsync("Test/?id="+ paramsValue).Result;
var textResponse = response.Content.ReadAsStringAsync().Result;
var result = JsonConvert.DeserializeObject<MyClass>(textResponse);
}
The problem is that the parameter id which is received by the controller is a default instance of MyClass (i.e. Value = 0). If I change the prototype of the method to accept a string:
[HttpGet]
public MyClass Other([FromUri]string id)
{
var val = JsonConvert.DeserializeObject<MyClass>(id);
val.Value++;
return val;
}
it all works fine, but I would rather not have to manually do the deserialization in every controller method.
I have tried many combinations of how I create the query string, so far having no luck.
It appears that the data is getting to the webApi correctly, but the deserialization is not happening, so I suspect that I have not configure the webApi correctly to use json form the request parameters.
my webapiconfig looks like:
public static void Register(HttpConfiguration config)
{
if (config == null)
throw new ArgumentNullException(nameof(config));
// Web API configuration and services
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
}
so its returning json correctly, but incoming parameters are not deserialized correctly.
Can anyone help??
