ASP.NET web api 2:字典总是反序列化为空?

时间:2018-06-09 22:55:53

标签: .net asp.net-web-api asp.net-web-api2

我正在发送一个字典,其中包含以下呼叫:

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();
}

我做错了什么?

如果我尝试获取请求的主体(string body = await Request.Content.ReadAsStringAsync();)并使用DataContractJsonSerializer手动反序列化,我会得到预期的词典。

0 个答案:

没有答案