3.71追加请求内容

创建于 2026 年 8 月 17 日约 2 分钟读完

当需要向已存在的请求内容中动态添加更多数据,而不影响已设置的 ContentTypeContentEncoding 时,可以使用 AppendContent() 方法。该方法会依据现有内容与传入内容的类型进行智能合并:

现有内容类型传入内容类型合并行为
stringstring使用 & 符号拼接(常用于 application/x-www-form-urlencoded
StringBuilderstring将传入字符串追加到 StringBuilder 末尾
IDictionary<string, object?>IDictionary<string, object?>合并两个字典,对已存在的键更新值
NameValueCollectionNameValueCollectionIDictionary<string, object?>合并键值对,同名键可保留多个值;字典值将转换为字符串后添加
IListIEnumerable (非字符串)将传入集合的元素依次追加到列表中
其他任意类型任意类型直接覆盖原有内容
cs
// 字符串拼接:一次调用追加,多次调用可连续追加HttpRequestBuilder.Post("https://furion.net/")    .SetContent("a=1", "application/x-www-form-urlencoded")    .AppendContent("b=2");    // 结果:a=1&b=2// StringBuilder 追加字符串var sb = new StringBuilder("a=1");HttpRequestBuilder.Post("https://furion.net/")    .SetContent(sb, "application/x-www-form-urlencoded")    .AppendContent("&b=2");   // sb 内容变为 "a=1&b=2"// 字典合并:已存在的键值会被更新var dict = new Dictionary<string, object?> { ["key1"] = "val1" };HttpRequestBuilder.Post("https://furion.net/")    .SetContent(dict, "application/x-www-form-urlencoded")    .AppendContent(new Dictionary<string, object?> { ["key2"] = "val2" }); // 合并为 { key1: val1, key2: val2 }// NameValueCollection 合并(同名键保留多个值)var nvc = new NameValueCollection { ["id"] = "1" };HttpRequestBuilder.Post("https://furion.net/")    .SetContent(nvc, "application/x-www-form-urlencoded")    .AppendContent(new NameValueCollection { ["name"] = "furion", ["name"] = "dotnet" }); // "name" 拥有两个值// 列表追加:将新元素添加到已有列表中var list = new List<string> { "item1" };HttpRequestBuilder.Post("https://furion.net/")    .SetContent(list, "application/json")    .AppendContent(new[] { "item2" });   // 结果:["item1", "item2"]// 其他类型覆盖:使用新内容替换旧内容HttpRequestBuilder.Post("https://furion.net/")    .SetContent("original")    .AppendContent(new { id = 1 });      // RawContent 变为 { id = 1 }