3.12查询参数
添加或修改 URL 查询参数。
设置查询参数(URL 参数)#
添加或修改 URL 查询参数。
HttpRequestBuilder.Get("https://furion.net/") .WithQueryParameter("id", 1) // 添加单个参数 .WithQueryParameter("date", DateTime.Now, format: "yyyyMMdd") // 支持 format 格式化 .WithQueryParameter("name", new[] { "furion", "monksoul" }) // 添加多个值,生成:name=furion&name=monksoul .WithQueryParameter("name", (object?)null) // 设置 null 值 .WithQueryParameter("r", () => DateTimeOffset.UtcNow.ToUnixTimeSeconds()) // 设置动态计算参数(用于防缓存) .WithQueryParameter("r", context => DateTimeOffset.UtcNow.ToUnixTimeSeconds()) // 设置动态计算参数(用于防缓存) .WithQueryParameters(new Dictionary<string, object?> { }) // 添加多个参数 .WithQueryParameters(new { id = 1, name = "Furion" }) // 添加多个参数,生成:id=1&name=Furion .WithQueryParameters(new { id = 1, name = "Furion" }, "user") // 添加带前缀的参数,生成:user.id=1&user.name=Furion .WithQueryParameters(new Dictionary<string, object?> { { "str1", null }, {"str2", "test" } }, ignoreNullValues: true); // 忽略空值若存在重复的查询参数键,它们将合并成多个键值对(如 key1=value1&key1=value2)。通过设置 replace: true 参数,可以覆盖先前的查询参数和原始 URL 地址参数。默认情况下,值为 null 的查询参数会被添加到 URL 中;若需忽略这些参数,可设置 ignoreNullValues: true。
URL 参数格式化程序#
在设置 HTTP 请求的查询参数时,框架会将参数键和值传递给 IUrlParameterFormatter 进行格式化。默认实现 UrlParameterFormatter 会为每个值生成一个 key=value 形式的键值对。但某些类型(如 DateTime)可能需要特殊处理,或希望改变整个键值对的输出形态(例如将多个值输出为 key[0]=val1&key[1]=val2 这样的数组格式),此时可以通过自定义格式化程序实现。
以下示例展示如何重写 Format 方法,以便将 DateTime 类型的值格式化为 yyyyMMdd 格式,其余类型使用默认处理:
public class CustomUrlParameterFormatter : UrlParameterFormatter{ /// <inheritdoc /> public override IEnumerable<KeyValuePair<string, string?>>? Format(UrlFormattingContext context, string key, IEnumerable<object?> values) { foreach (var value in values) { if (value is DateTime dateTime) { yield return new(key, dateTime.ToString("yyyyMMdd")); // 格式化 continue; } yield return new(key, FormatValue(context, value)); } }}完成自定义格式化程序后,可以在配置 HttpRemoteOptions 时将其注册为默认的 URL 参数格式化器:
services.AddHttpRemote(builder => {}) .ConfigureOptions(options => { options.UrlParameterFormatter = new CustomUrlParameterFormatter(); });如此一来,在构建 URL 查询参数时,若遇到 DateTime 类型的值,框架将自动将其格式化为 yyyyMMdd 格式的字符串,从而确保输出符合预期。
URL 参数排序#
尽管对 URL 查询参数排序的需求相对少见,但在一些对安全性要求较高的系统中,往往需要验证参数的顺序。框架为此提供了排序支持,排序对象为最终的键值对集合:
HttpRequestBuilder.Get("https://furion.net/") .WithQueryParameters(new { name = "furion", id = 1}) .SetQueryParametersSorter(pairs => pairs.OrderBy(kv => kv.Key));通过 .SetQueryParametersSorter() 方法配置查询参数排序规则。该方法接收一个 KeyValuePair<string, string?> 序列,返回排序后的新序列。为 null 时不排序(原始添加顺序)。
设置移除的查询参数#
移除指定的查询参数。
HttpRequestBuilder.Get("https://furion.net/") .RemoveQueryParameters("id", "name", "age"); // 移除多个参数在发送 HTTP 请求之前,将移除配置中指定的待移除查询参数集合。也就是说,RemoveQueryParameters 方法会在所有 WithQueryParameter[s] 方法调用之后执行。