通过使用可以轻松限制 api 的速率,
<rate-limit-by-key calls="3" renewal-period="15" counter-key="@(context.Subscription.Id)" />
但是我需要通过使用 apiKey 作为请求参数发送来限制 api 的速率。
首先,我从您的示例中假设您希望将请求本身的一个元素指定为
counter-key
而不是订阅 ID(如示例中所示)。如果这是正确的,那么...
counter-key
的示例。
<policies>
<inbound>
<base />
<rate-limit-by-key calls="10"
renewal-period="60"
increment-condition="@(context.Response.StatusCode == 200)"
counter-key="@(context.Request.IpAddress)"
remaining-calls-variable-name="remainingCallsPerIP"/>
</inbound>
<outbound>
<base />
</outbound>
</policies>
假设您提到的 API 密钥将作为请求标头传入,看起来您可以执行以下操作:
<rate-limit-by-key counter-key='@(context.Request.Headers.TryGetValue("YourApiKey"))' ... />
如果您想处理 ApiKey 根本不包含在请求中的情况,看起来您可以使用多行策略表达式:
<rate-limit-by-key
counter-key='@{
if (context.Request.Headers.TryGetValue("YourApiKey", out value))
{
if(value != null && value.Length > 0)
{
return value;
}
}
return null;
}'
calls='@{
if (context.Request.Headers.TryGetValue("YourApiKey", out value))
{
if(value != null && value.Length > 0)
{
return 500;
}
}
return 0;
}'
...
/>
注意:我没有在这里测试任何建议的策略,但我认为这里的最后一个策略将允许每个
{YourApiKey}
每个周期 500 个请求,如果未提供 Api 密钥,则不会允许任何请求.
假设您将 api-key 作为标头传递(这是最佳实践,来源:将 API 密钥放在标头或 URL 中),速率限制应如下所示:
<rate-limit-by-key calls="3" renewal-period="15" counter-key="@(context.Request.Headers.GetValueOrDefault("x-api-key", "default-value"))" />