使用 formurlencodedcontent 配合 httpclient.postasync 即可发送标准的表单数据。只需将键值对放入 list<keyvaluepair string>></keyvaluepair> 中构造内容对象,调用 post 方法后框架会自动处理 url 编码和 content-type 头设置。

FormUrlEncodedContent 如何处理特殊字符编码?
该类在序列化时会对非字母数字字符进行百分号编码(Percent-encoding),例如空格会被转换为 %20,这符合 application/x-www-form-urlencoded 规范。如果手动拼接字符串而未正确转义,服务器端解析时会出错,因此推荐使用内置类来保证编码一致性。

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
using var client = new HttpClient();
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", "admin"),
new KeyValuePair<string, string>("password", "p@ss w0rd!")
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://example.com/login", content);
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
如何验证请求头中的 Content-Type 是否正确设置?
FormUrlEncodedContent 构造函数会自动将 ContentType 属性设置为 application/x-www-form-urlencoded; charset=utf-8。开发者无需手动添加该 Header,若手动覆盖可能导致服务器无法正确解析 Body 中的参数。通过检查响应或抓包工具可确认此行为。

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
using var client = new HttpClient();
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("key", "value")
};
var content = new FormUrlEncodedContent(values);
// 验证 ContentType 是否自动设置
Console.WriteLine(content.Headers.ContentType);
var response = await client.PostAsync("https://example.com/api", content);
}
}
当表单中包含重复键名时,FormUrlEncodedContent 的行为是什么?
在构造 FormUrlEncodedContent 时,如果 List<keyvaluepair string>></keyvaluepair> 中包含相同的键名,它们会被依次编码并追加到查询字符串中,用 & 分隔。例如两个 id=1 会变成 id=1&id=1。这种处理方式兼容大多数后端框架对数组参数的解析逻辑,但具体解析结果取决于服务端实现。


















