初始化 HttpRequest 标头时出现编译错误

问题描述 投票:0回答:1

我正在尝试基于一些Python代码初始化

HttpClient

尝试在 python 代码中为“数据”标头创建自定义标头时遇到编译器错误:

无法从“System.Collections.Generic.Dictionary”转换为“System.Collections.Generic.IEnumerable

“headers”标题的自定义标题相同:

无法从“System.Collections.Generic.KeyValuePair”转换为“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 代码一样运行?

c# http-headers reddit
1个回答
0
投票

文档:https://learn.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);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.