[英]How to deserialize parameter from json in webapi controller
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: 我有一个mvc webapi控制器:
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: 我正在从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 (ie Value = 0). 问题是控制器接收的参数
id
是MyClass的默认实例(即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. 似乎数据正确到达webApi,但反序列化没有发生,所以我怀疑我没有正确配置webApi以使用json形式的请求参数。
my webapiconfig looks like: 我的webapiconfig看起来像:
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. 所以它正确返回json,但传入的参数没有正确反序列化。
Can anyone help?? 谁能帮忙?
Thanks to the help from @Mostafizur Rahman, I came to the conclusion that a get method was not appropriate here, So I have changed to a Post method and pass the data in the body: 感谢@Mostafizur Rahman的帮助,我得出的结论是get方法在这里不合适,所以我已经改为Post方法并将数据传递到正文中:
public class TestController : ApiController
{
public MyClass PostMethod([FromBody]MyClass id)
{
id.Value++;
return id;
}
}
public class MyClass
{
public int Value {get;set;}
}
with the client side becoming: 与客户端成为:
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.PostAsync("Test/PostMethod", queryString).Result;
var textResponse = response.Content.ReadAsStringAsync().Result;
var result = JsonConvert.DeserializeObject<MyClass>(textResponse);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.