我正在尝试基于一些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 代码一样运行?
文档: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);
}
}
}