webapi限流框架WebApiThrottle

为了防止网站意外暴增的流量比如活动、秒杀、攻击等,导致整个系统瘫痪,在前后端接口服务处进行流量限制是非常有必要的。本篇主要介绍下Net限流框架WebApiThrottle的使用。

WebApiThrottle是一个专门为webApi限制请求频率而设计的,支持寄宿OWIN上的中间件的限制过滤。服务端接口可以基于客户端请求IP地址、客户端请求key、及请求路由去限制webapi接口的访问频率。

下面的代码是限制来自同IP请求的最大次数。如果在一分钟内,同样IP的客户端分别调用api/values和api/values/1两个接口, 那么调用api/values/1的请求会被拒绝掉。

IP和客户端key自定义限制频率

复制代码
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MessageHandlers.Add(new ThrottlingHandler()
        {
            Policy = new ThrottlePolicy(perSecond: 1, perMinute: 20, perHour: 200, perDay: 1500, perWeek: 3000)
            {
                IpThrottling = true
            },
            Repository = new CacheRepository()
        });
    }
}
复制代码
复制代码
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()
});
复制代码

 

 

用ThrottlingFilter、EnableThrottlingAttribute特性配置限制频率

EnableThrottling与ThrottlingHandler是一个二选一的策略配置方案,二者会做同样的事情,但ThrottlingHandler可以通过EnableThrottlingAttribute特性指定某个webapi的controllers和actions去自定义频率限制。需要注意的是,在webapi请求管道中,ThrottlingHandler是在controller前面执行,因此在你不需要ThrottlingFilter提供的功能时,可以用ThrottlingHandler去直接替代它。

设置ThrottlingFilter过滤器的步骤,跟ThrottlingHandler类似

复制代码
 public static class WebApiConfig
    { 
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务
      

            config.SuppressDefaultHostAuthentication();

           
            config.Filters.Add(new CustomerThrottlingFilter()
            {
                Policy = new ThrottlePolicy(perMinute: 15)
                {
                    //scope to IPs
                    IpThrottling = false,

                    //scope to clients (if IP throttling is applied then the scope becomes a combination of IP and client key)
                    ClientThrottling = true,

                    //white list API keys that don’t require throttling
                    ClientWhitelist = new List<string> { "admin-ll" },

                    //Endpoint rate limits will be loaded from EnableThrottling attribute
                    EndpointThrottling = true
                }
            });

 

        }
    }
复制代码

获取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()
        };
    }
}
复制代码

 

posted @   桃花雪  阅读(2900)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示