如何用Flurl传递多个同键的URL编码表单参数?
如何用Flurl实现带重复键的表单参数POST请求
需要复刻的curl请求如下:
curl -X POST \ https://example.com \ --data "itemDescriptions=item 1" \ --data "itemDescriptions=item 2"
不可行的方案
- 匿名对象方式:C#匿名对象不允许存在重复键,直接编译报错:
"https://example.com".PostUrlEncodedAsync(new { itemDescriptions = "item 1", itemDescriptions = "item 2" });
- KeyValuePair列表方式(旧版Flurl存在问题):尝试用列表传递重复键时,请求仅会发送列表最后一个参数,且服务器不接受带
[]的参数名:
var formValues = new List<KeyValuePair<string,string>>() { new KeyValuePair<string, string>("itemDescriptions", "item 1"), new KeyValuePair<string, string>("itemDescriptions", "item 2") }; "https://example.com".PostUrlEncodedAsync(formValues);
正确解决方案
方案1:使用FormUrlEncodedContent构建请求体
直接借助FormUrlEncodedContent原生支持重复键的特性,通过Flurl的PostAsync发送请求:
using System.Net.Http; using Flurl.Http; var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("itemDescriptions", "item 1"), new KeyValuePair<string, string>("itemDescriptions", "item 2") }); await "https://example.com".PostAsync(formContent);
方案2:升级Flurl后用列表传递
如果使用Flurl v3.x及以上版本,直接传递KeyValuePair列表即可,新版本已修复重复键合并的问题:
var formValues = new List<KeyValuePair<string, string>>() { new("itemDescriptions", "item 1"), new("itemDescriptions", "item 2") }; await "https://example.com".PostUrlEncodedAsync(formValues);
方案3:手动拼接表单内容(适配旧版Flurl)
如果无法升级Flurl版本,可手动编码表单字符串,再用StringContent发送:
var formString = "itemDescriptions=item%201&itemDescriptions=item%202"; var content = new StringContent(formString, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded"); await "https://example.com".PostAsync(content);
内容的提问来源于stack exchange,提问作者Luke
相关产品推荐
相关产品推荐

