ASP.NET Core WebApi AspNetCoreRateLimit 限流中间件简单使用
- AspNetCoreRateLimit 介绍说明:
麻烦各位看官移步官网介绍直通车:https://github.com/stefanprodan/AspNetCoreRateLimit
- Startup文件限流控制代码演示
public void ConfigureServices(IServiceCollection services)
{
//首先nuget安装 Install-Package AspNetCoreRateLimit 2.0.0
services.AddOptions();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//需要存储速率和ip规则
services.AddMemoryCache();
//加载appsettings.json中的配置项 ,下面三项是加载general,rules
//services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
//services.Configure<IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies"));
services.Configure<IpRateLimitOptions>(options =>
{
options.HttpStatusCode = 429; //限流后返回的http状态码
options.QuotaExceededMessage = "请求过于频繁";//自定义限流后返回的http消息
options.GeneralRules = new List<RateLimitRule>
{
//里配置的是IP限制,它允许有很多规则,这里我只用了一个:针对所有的资源,每5秒最多3次请求。
new RateLimitRule
{
Endpoint="*",//所有
Limit=3,//配额
Period="5s"//间隔
}
};
});
//注入计时器和规则
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
//添加框架服务
services.AddMvc();
}
- Postman调用展示
- 3.1 请求频繁示例