HttpClient如何对嵌套字典进行POST请求

3
我遇到了一个错误:

严重程度状态码 描述 项目 文件 行号 抑制状态 错误 CS1503 第1个参数:无法从'System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, string>>'转换为'System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, string>>

当我使用 HttpClient 提交嵌套字典时。
var arg_employee = new Dictionary<string, Dictionary<string, string>>
{
    {
        "filter_data",
        new Dictionary<string, string>
        {
            {"user_name", "admin"},
        }
    },
};

var content = new FormUrlEncodedContent(arg_employee);
// ... Use HttpClient.
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(uRL, content))
using (HttpContent responseContent = response.Content)
{
    // ... Read the string.
    return await responseContent.ReadAsStringAsync();

我该如何发布嵌套字典或数组?

1
很抱歉,这是不可能的。您正在发送FormUrlEncodedContent。您可以将此类复杂对象作为JSON或XML发送。 - Ali Bahrami
1个回答

2
"最初的回答" 被翻译为:FormUrlEncodedContent 接受 IEnumerable<KeyValuePair<string, string>> nameValueCollection,而不是 Dictionary。请参见此链接
如果要传递字典,您应该将其序列化为 JSON,例如:
第一步,使用 Newtonsoft.Json(您可以手动序列化或使用另一个库)获取字典的 JSON 表示形式。
using Newtonsoft.Json

var arg_employee = new Dictionary<string, Dictionary<string, string>>
{
    {
        "filter_data",
        new Dictionary<string, string>
        {
            {"user_name", "admin"},
        }
    },
};

var jsonDictionary = JsonConvert.SerializeObject(arg_employee );

第二步,将其作为StringContent而不是FormUrlEncodedContent发布: "最初的回答"
var content = new StringContent(jsonDictionary , Encoding.UTF8, "application/json");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接