1. 程式人生 > >WebApiThrottle限流框架——IP和客戶端key自定義限制頻率

WebApiThrottle限流框架——IP和客戶端key自定義限制頻率

你可以自定義基於ip或客戶端key的請求頻率限制,這些限制會重寫WebApiThrottle的預設配置。

需要注意的是,這些自定義策略需要寫到全域性配置裡才會生效,策略裡可以單獨給某個ip或某個key配置限流策略。

config.MessageHandlers.Add(new ThrottlingHandler()
{
    Policy = new ThrottlePolicy(perSecond: 1, perMinute: 20, perHour: 200, perDay: 1500)
    {
        IpThrottling = true,
        IpRules = new Dictionary<string, RateLimits>
        { 
            { "192.168.1.1", new RateLimits { PerSecond = 2 } },
            { "192.168.2.0/24", new RateLimits { PerMinute = 30, PerHour = 30*60, PerDay = 30*60*24 } }
        },

        ClientThrottling = true,
        ClientRules = new Dictionary<string, RateLimits>
        { 
            { "api-client-key-1", new RateLimits { PerMinute = 40, PerHour = 400 } },
            { "api-client-key-9", new RateLimits { PerDay = 2000 } }
        }
    },
    Repository = new CacheRepository()
});