首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >ASP.NET web api 2:字典总是反序列化为空?

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

Stack Overflow用户
提问于 2019-01-04 04:30:01
回答 1查看 0关注 0票数 0

我正在发送一个带有如下调用的字典:

代码语言:javascript
复制
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;
}

我看到在接收端,字典总是被反序列化为空。

代码语言:javascript
复制
[HttpPost]
public IHttpActionResult Test(Dictionary<string, string> req)
{
    return Ok();
}

我究竟做错了什么?

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

EN

回答 1

Stack Overflow用户

发布于 2019-01-04 14:01:15

你丢失了FromBody属性:

代码语言:javascript
复制
[HttpPost]
public IHttpActionResult Test([FromBody] Dictionary<string, string> req)
{
    return Ok();
}

FromBody告诉框架检查Content-Type标头以确定IInputFormatter应该使用哪个绑定该参数。在你的情况下,这将使它使用JsonInputFormatterdeserialise req,它应该正确地为你绑定字典。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100005151

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档