我正在发送一个带有如下调用的字典:
public async Task<string> Test(string val1, string val2)
{
string res = null;
using (HttpClient http = new HttpClient())
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("value1", val1);
dic.Add("value2", val2);
string data = JsonHelper.Serialize<Dictionary<string, string>>(dic);
using (StringContent content = new StringContent(data, Encoding.UTF8, "application/json"))
{
Uri uri = new Uri("http://www.whatever.com/api/test");
using (HttpResponseMessage response = await http.PostAsync(uri, content))
{
res = await response.Content.ReadAsAsync<string>();
}
}
}
return res;
}
我看到在接收端,字典总是被反序列化为空。
[HttpPost]
public IHttpActionResult Test(Dictionary<string, string> req)
{
return Ok();
}
我究竟做错了什么?
如果我尝试获取request(string body = await Request.Content.ReadAsStringAsync();
)的主体并使用DataContractJsonSerializer手动反序列化,我会得到预期的Dictionary。
发布于 2019-01-04 14:01:15
你丢失了FromBody
属性:
[HttpPost]
public IHttpActionResult Test([FromBody] Dictionary<string, string> req)
{
return Ok();
}
FromBody
告诉框架检查Content-Type
标头以确定IInputFormatter
应该使用哪个绑定该参数。在你的情况下,这将使它使用JsonInputFormatter
deserialise req
,它应该正确地为你绑定字典。
https://stackoverflow.com/questions/-100005151
复制相似问题