You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于API需求为不同API添加策略(Terraform+XML场景)

问题分析与解决方案

你的代码问题在于两个<when>条件没有区分具体API,只要请求的ApiKey是"Default",就会触发第一个限流规则,第二个规则永远不会被执行。要实现不同API对应不同策略,必须在条件里明确判断当前请求所属的API。

修正思路

  • 用context.Api.Name(或context.Api.Id,更稳定)来标识不同API,确保每个策略只对目标API生效
  • 让两个API的条件互斥,避免规则覆盖

修正后的代码示例

假设API ONE的名称是"API_One",API TWO的名称是"API_Two",调整后的策略如下:

<choose>
    ########## API ONE ###########
    <when condition="@(context.Api.Name == \"API_One\" && context.Request.Headers.GetValueOrDefault(\"ApiKey\") == \"Default\")">
        <rate-limit-by-key calls="10" renewal-period="60" counter-key="@(context.Request.IpAddress)" />
    </when>
    ########## API TWO ###########
    <when condition="@(context.Api.Name == \"API_Two\" && context.Subscription.Name.Contains(\"API_name\") && context.Request.Headers.GetValueOrDefault(\"ApiKey\") == \"Default\")">
         <rate-limit-by-key calls="2000" renewal-period="60" counter-key="@(context.Request.Headers.GetValueOrDefault(\"Authorization\",\"\").AsJwt()?.Subject)" />
     </when>
     <otherwise>
          <rate-limit-by-key calls="10000" renewal-period="60" counter-key="@(context.Subscription.Id)" />
     </otherwise>
</choose>

关键说明

  • API标识判断:通过context.Api.Name精准匹配目标API,避免规则串用
  • 条件互斥:每个<when>都限定了对应API,不会出现第一个规则覆盖第二个的情况
  • 可选优化:如果用API的ID(context.Api.Id)替代名称,能避免API名称变更导致策略失效,稳定性更高

内容的提问来源于stack exchange,提问作者Panda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 18:44:54