初始化 HttpRequest 时编译错误 headers

Compile error while initializing HttpRequest headers

我正在尝试根据一些 python 代码初始化一个 HttpClient

我在尝试为 python 代码中的 'data' header 创建自定义 header 时遇到编译器错误:无法从 [=27= 转换] 到 'System.Collections.Generic.IEnumerable

“headers”header 的自定义 header 相同:无法从 'System.Collections.Generic.KeyValuePair<string, string>' 转换为 'System.Collections.Generic.IEnumerable

C#代码

            Dictionary<string, string> data = new Dictionary<string, string>()
            {
                {"grant_type", "password" },
                {"username", Username },
                {"password", Password }
            };
            tokenApiClient.DefaultRequestHeaders.Add("data", data); Compiler Error: cannot convert from 'System.Collections.Generic.Dictionary<string, string>' to 'System.Collections.Generic.IEnumerable<string?>

            KeyValuePair<string, string> headers = new KeyValuePair<string, string>("User-Agent", "Post analysis for neural network text generation.");
            tokenApiClient.DefaultRequestHeaders.Add("headers", headers); // Compile Error: cannot convert from 'System.Collections.Generic.KeyValuePair<string, string>' to 'System.Collections.Generic.IEnumerable<string?>'

Python代码

data = {
    'grant_type': 'password',
        'username': '<USERNAME>',
        'password': '<PASSWORD>'}

headers = { 'User-Agent': 'MyBot/0.0.1'}

res = requests.post('https://www.reddit.com/api/v1/access_token',
        auth=auth, data=data, headers=headers)

如何初始化它,使其像 python 代码一样运行?

文档:https://docs.microsoft.com/en-us/dotnet/api/system.net.http.headers.httpheaders.add?view=net-5.0

Add 方法签名接受 (string, string)(string, IEnumerable<string>)

看来您必须遍历字典并为每个字典项调用添加。

您还可以创建一些方便的扩展方法,例如:

public static class MyHttpExtensions 
{
    public static void Add(this HttpHeaders header, IDictionary<string, string> dictTable) 
    {
        foreach (var item in dictTable) 
        {
            header.Add(item.Key, item.Value);
        }
    }
}