我正在嘗試HttpClient根據一些 python 代碼初始化一個。
嘗試為 python 代碼中的“資料”標頭創建自定義標頭時出現編譯器錯誤:無法從“System.Collections.Generic.Dictionary<string, string>”轉換為“System.Collections.Generic.IEnumerable” <字串?>
與“headers”標頭的自定義標頭相同:無法從 'System.Collections.Generic.KeyValuePair<string, string>' 轉換為 'System.Collections.Generic.IEnumerable<string?>
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 代碼一樣作業?
uj5u.com熱心網友回復:
檔案:https : //docs.microsoft.com/en-us/dotnet/api/system.net.http.headers.httpheaders.add? view = net- 5.0
Add 方法簽名接受(string, string)或(string, IEnumerable<string>)。
看起來您必須遍歷字典并為每個字典項呼叫 Add 。
您還可以創建一些方便的擴展方法,例如:
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);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/342842.html
上一篇:在這里,當我按下一個有效的空格時,我試圖更改DirectionX的值,但我必須多次按下才能更改
下一篇:如何在老虎機C#中隨機化影像
