如何使API Management的set-query-parameter策略大小写不敏感生效?
API Manager 查询参数大小写不敏感处理及参数验证配置方案
一、解决set-query-parameter策略大小写不敏感问题
默认的set-query-parameter对参数名大小写敏感,无法覆盖大小写变体的参数。可以通过先统一查询参数键的大小写、清理变体参数,再设置固定值的方式解决:
<!-- 1. 将所有查询参数键转为小写并去重 --> <set-variable name="lowercaseQueryParams" value="@(context.Request.Query.Select(q => new KeyValuePair<string, string>(q.Key.ToLowerInvariant(), q.Value)).GroupBy(q => q.Key).ToDictionary(g => g.Key, g.First().Value))" /> <!-- 2. 重写URI,移除所有大小写变体的myParameter参数 --> <set-variable name="filteredQueryString" value="@(string.Join("&", context.Variables.GetValueOrDefault<Dictionary<string, string>>("lowercaseQueryParams").Where(q => q.Key != "myparameter").Select(q => $"{Uri.EscapeDataString(q.Key)}={Uri.EscapeDataString(q.Value)}")))" /> <rewrite-uri template="@(context.Request.Url.Path)" copy-unmatched-params="false" query-string="@(context.Variables.GetValueOrDefault<string>("filteredQueryString"))" /> <!-- 3. 设置固定值的myParameter --> <set-query-parameter name="myParameter" exists-action="override"> <value>myFixedValue</value> </set-query-parameter>
该逻辑会将所有查询参数的键转为小写,过滤掉myparameter(小写)的所有变体,再统一设置固定值的myParameter,确保无论传入何种大小写形式的参数,最终都会被覆盖为指定值。
二、调整validate-parameters配置实现预期验证逻辑
你的需求是放行所有请求头、路径参数,仅允许myParameter(含大小写变体)作为查询参数。由于validate-parameters本身不支持大小写不敏感的参数名匹配,需要先统一查询参数键的大小写,再进行验证:
<!-- 先统一查询参数键为小写 --> <set-variable name="normalizedQueryParams" value="@(context.Request.Query.Select(q => new KeyValuePair<string, string>(q.Key.ToLowerInvariant(), q.Value)).GroupBy(q => q.Key).ToDictionary(g => g.Key, g.First().Value))" /> <rewrite-uri template="@(context.Request.Url.Path)" copy-unmatched-params="false" query-string="@(string.Join("&", context.Variables.GetValueOrDefault<Dictionary<string, string>>("normalizedQueryParams").Select(q => $"{Uri.EscapeDataString(q.Key)}={Uri.EscapeDataString(q.Value)}")))" /> <!-- 执行参数验证 --> <validate-parameters specified-parameter-action="ignore" unspecified-parameter-action="prevent" errors-variable-name="validationErrors"> <headers specified-parameter-action="ignore" unspecified-parameter-action="ignore"/> <query specified-parameter-action="ignore" unspecified-parameter-action="prevent"> <parameter name="myparameter" action="ignore" /> </query> <path specified-parameter-action="ignore"/> </validate-parameters>
说明:
- 先将所有查询参数键转为小写,确保
MyParameter、mYpAraMeTeR等变体都被统一为myparameter - 验证阶段仅允许
myparameter作为查询参数,其他参数会被阻止 - 请求头和路径参数保持完全放行的配置不变
内容的提问来源于stack exchange,提问作者BurningMetal
相关产品推荐
相关产品推荐

