Azure APIM出站策略中无法在响应头复用速率限制值
解决Azure APIM出站策略中剩余速率调用次数的类型转换错误
问题根源
你遇到的500错误是因为rate-limit-by-key策略会将剩余调用次数以Int32类型存入X-Rate-Limit-Remaining变量,直接用(string)强制转换整数类型会抛出类型转换异常。
修正后的完整策略代码
<!-- IMPORTANT: - Policy elements can appear only within the <inbound>, <outbound>, <backend> section elements. - To apply a policy to the incoming request (before it is forwarded to the backend service), place a corresponding policy element within the <inbound> section element. - To apply a policy to the outgoing response (before it is sent back to the caller), place a corresponding policy element within the <outbound> section element. - To add a policy, place the cursor at the desired insertion point and select a policy from the sidebar. - To remove a policy, delete the corresponding policy statement from the policy document. - Position the <base> element within a section element to inherit all policies from the corresponding section element in the enclosing scope. - Remove the <base> element to prevent inheriting policies from the corresponding section element in the enclosing scope. - Policies are applied in the order of their appearance, from the top down. - Comments within policy elements are not supported and may disappear. Place your comments between policy elements or at a higher level scope. --> <policies> <inbound> <base /> <!-- 可移除该行空值初始化,rate-limit-by-key会自动创建并赋值变量 --> <!-- <set-variable name="X-Rate-Limit-Remaining" value="" /> --> <rate-limit-by-key calls="5" renewal-period="10" counter-key="@(context.Subscription?.Key)" increment-condition="@(context.Response.StatusCode == 200)" remaining-calls-variable-name="X-Rate-Limit-Remaining" /> </inbound> <backend> <base /> </backend> <outbound> <base /> <set-header name="X-Rate-Limit-Remaining" exists-action="append"> <!-- 使用ToString()方法将整数转换为字符串 --> <value>@(((int)context.Variables["X-Rate-Limit-Remaining"]).ToString())</value> <!-- 也可使用简洁的字符串插值写法:<value>@($"{context.Variables["X-Rate-Limit-Remaining"]}")</value> --> </set-header> </outbound> <on-error> <base /> </on-error> </policies>
关键修改点
- 移除冗余的变量初始化:
rate-limit-by-key策略会自动创建remaining-calls-variable-name指定的变量并赋值,无需提前用空字符串初始化,避免变量类型被强制设为string。 - 正确转换整数到字符串:
- 先将变量强制转换为
int类型,再调用ToString()方法转为字符串 - 或者直接使用C#字符串插值语法
$"{变量}",自动完成类型转换
- 先将变量强制转换为
额外说明
如果订阅密钥不存在(比如匿名访问场景),context.Subscription?.Key会返回null,此时rate-limit-by-key会使用统一的计数器。若需针对匿名请求单独处理,可添加对应的判断逻辑。
内容的提问来源于stack exchange,提问作者PavanKumar GVVS
相关产品推荐
相关产品推荐

