1. 程式人生 > >WebApiThrottle限流框架——獲取API的客戶端key

WebApiThrottle限流框架——獲取API的客戶端key

預設情況下,WebApiThrottle的ThrottlingHandler(限流處理器)會從客戶端請求head裡通過Authorization-Token key取值。如果你的API key儲存在不同的地方,你可以重寫ThrottlingHandler.SetIndentity方法,指定你自己的取值策略。

public class CustomThrottlingHandler : ThrottlingHandler
{
    protected override RequestIdentity SetIndentity(HttpRequestMessage request)
    {
        return new RequestIdentity()
        {
            ClientKey = request.Headers.Contains("Authorization-Key") ? request.Headers.GetValues("Authorization-Key").First() : "anon",
            ClientIp = base.GetClientIp(request).ToString(),
            Endpoint = request.RequestUri.AbsolutePath.ToLowerInvariant()
        };
    }
}