5.23设置 HttpRequestMessage 属性
创建于 2026 年 8 月 17 日约 3 分钟读完
在特定场景下,我们可能需要为 HttpRequestMessage 请求添加额外的属性,而非通过请求标头。
HTTP 声明式请求通过 PropertyAttribute 特性来设置 HttpRequestMessage 请求属性。相应的 HTTP 声明式提取器实现为 PropertyDeclarativeExtractor 类型,该类型负责解析 PropertyAttribute 特性并构建 HttpRequestBuilder 实例所需的 HttpRequestMessage 请求属性配置。
利用 PropertyAttribute 特性,可以便捷地在接口、方法或参数上添加 HttpRequestMessage 请求属性。
// 在接口定义上应用,影响所有方法[Property("property1", "value1")][Property("property2", "value2")][Property("property0")] // 值为 nullpublic interface IHttpService : IHttpDeclarative{ // 在方法上应用 [Property("property3", "value3")] [Property("property4", "value4")] [Get("https://furion.net/")] Task<string> GetStringAsync(); // 在参数上应用,支持 AliasAs 属性指定别名,且可多重指定 [Property("property3", "value3")] [Get("https://furion.net/")] Task<string> GetStringAsync([Property] string property4, [Property][Property(AliasAs = "property5")] int lastProperty); // 在参数上可通过 Value 属性设定默认值,同样可为 age 参数设定,例如 int? age = 30 [Get("https://furion.net/")] Task<string> GetStringAsync([Property(Value = 30)] int? age); // 支持 [AliasAs] 定义别名 [Get("https://furion.net/")] Task<string> GetStringAsync([Property][AliasAs("property5")] int lastProperty); // 添加对象内容,AsItem 为 false 时,对象会被解析并遍历,其属性将作为独立的 HttpRequestMessage 请求属性项进行设置 [Get("https://furion.net/")] Task<string> GetStringAsync([Property(AsItem = false)] object obj); // 冻结参数类型将被忽略 [Get("https://furion.net/")] Task<string> GetStringAsync([Property] CancellationToken cancellationToken);}这些属性会被添加到 HttpRequestMessage 对象的 Options 属性中(参考文档)。要获取这些值,可以这样做:
httpRequestMessage.Options.TryGetValue(new HttpRequestOptionsKey<string>("key1"), out var value);若属性键出现重复,则后设置的键值会覆盖先前的设置。
PropertyAttribute 包含以下构造函数和属性:
-
构造函数:
new():作用于参数时有效,表示添加HttpRequestMessage请求属性,默认键为参数名。new(name):作用于方法或接口时,则表示添加HttpRequestMessage请求属性操作,值为null;作用于参数时,表示添加HttpRequestMessage请求属性,键为参数name的值。new(name, value):作用于接口、方法或参数,表示添加HttpRequestMessage请求属性,键为参数name的值,优先级低于AliasAs属性。
-
属性:
Name:HttpRequestMessage请求属性键(string类型),优先级低于AliasAs属性。Value:HttpRequestMessage请求属性的值(object类型),当特性作用于参数时,表示默认值。AliasAs:HttpRequestMessage请求属性键别名(string类型),优先级高于Name属性。AsItem:表示是否作为HttpRequestMessage请求属性的一项(bool类型),默认值为true(作为),仅当参数为对象类型时有效。为false(不作为) 时,对象会被解析并遍历,其属性将作为独立的HttpRequestMessage请求属性项进行设置。