我创建了一个KeyValuePair列表,用于填充内容作为HttpClient的数据。
List<KeyValuePair<string, string>> keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>("email", email));
keyValues.Add(new KeyValuePair<string, string>("password", password));
keyValues.Add(new KeyValuePair<string, string>("plan_id", planId));
var content = new FormUrlEncodedContent(keyValues);
但后来我发现我必须发送一个int值作为plan_id。如何更改上面的列表以接受KeyValuePair。或者有更好的方法吗?
答案 0 :(得分:0)
如果要创建KeyValuePair列表,则应创建词典。
Dictionary<string, string> dic = new Dictionary<string,string>();
dic.Add("email", email);
dic.Add("password", password);
dic.Add("plan_id", planId.ToString());
答案 1 :(得分:0)
请勿使用List<KeyValuePair<string,string>>
,而不是Dictionary<string, string>
。使用planId.ToString()。
答案 2 :(得分:0)
使用FormUrlEncodedContent时,使用KeyValuePair<string, object>
放置值并创建或转换列表到KeyValuePair<string, string>
List<KeyValuePair<string, object>> keyValues = new List<KeyValuePair<string, object>>();
keyValues.Add(new KeyValuePair<string, object>("email", "asdasd"));
keyValues.Add(new KeyValuePair<string, object>("password", "1131"));
keyValues.Add(new KeyValuePair<string, object>("plan_id", 123));
keyValues.Add(new KeyValuePair<string, object>("other_field", null));
var content = new FormUrlEncodedContent(keyValues.Select(s =>
new KeyValuePair<string, string>(s.Key, s.Value != null ? s.ToString() : null)
));
public static KeyValuePair<string, string> ConvertRules(KeyValuePair<string, object> kv)
{
return new KeyValuePair<string, string>(kv.Key, kv.Value != null ? kv.ToString() : null);
}
static Task Main(string[] args)
{
List<KeyValuePair<string, object>> keyValues = new List<KeyValuePair<string, object>>();
keyValues.Add(new KeyValuePair<string, object>("email", "asdasd"));
keyValues.Add(new KeyValuePair<string, object>("password", "1131"));
keyValues.Add(new KeyValuePair<string, object>("plan_id", 123));
keyValues.Add(new KeyValuePair<string, object>("other_field", null));
var content = new FormUrlEncodedContent(keyValues.ConvertAll(ConvertRules)));
));