1、在接口项目nutget中找到AspNetCoreRateLimit组件
![](https://i-blog.csdnimg.cn/blog_migrate/0748765d0c6d29d19eea10d1d48e9231.png)
2、在appsettings.json中配置以下内容
![](https://i-blog.csdnimg.cn/blog_migrate/7ab09afc60c57f6c4b3889ec0ffdec4b.png)
"IpRateLimiting": {
//当为True的时候 例如设置了5次每分钟访问限流,当你getData()5次过后禁止访问,但是还可以访问postData()5次,
//总得来说是每个接口都有5次在这一分钟,互不干扰。"当为False的时候" "每个接口都加入计数,不管你访问哪个接口","只要在一分钟内累计够5次" "将禁止访问",
"EnableEndpointRateLimiting": true,
"StackBlockedRequests": false,
"RealIpHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"IpWhitelist": null,
"EndpointWhitelist": null,
"HttpStatusCode": 429,
"QuotaExceededResponse": {
"Content": "{{ \"message\": \"Too many requests,Please try again in {2} second(s).\", \"code\": 429,\"data \":\"\"}}",
"ContentType": "application/json"
},
"GeneralRules": [
{
"Endpoint": "*",
"Period": "4s",
"Limit": 1
}
]
}
3、在Startup.cs中ConfigureServices方法中添加配置
![](https://i-blog.csdnimg.cn/blog_migrate/269a118881d2dd3afe6e15e09b9bf6b0.png)
#region 限流配置
//加载配置
services.AddOptions();
//services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);//设置兼容性版本
services.AddMemoryCache();
//加载IpRateLimiting配置
services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
//注入计数器和规则存储
services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
//添加框架服务
services.AddMvc();
// clientId / clientIp解析器使用它。
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//配置(计数器密钥生成器)
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
#endregion
4、在Startup.cs中Configure方法中注册使用中间件
![](https://i-blog.csdnimg.cn/blog_migrate/bd24821d6ff9cf01f013b81c90d4ea07.png)
app.UseIpRateLimiting();
注意,可以自定义中间件来指定返回的信息,即在appsettings.json中IpRateLimiting节点下面的QuotaExceededResponse信息,方法如下:
在项目中自定义添加一个IPLimitMiddleware类,然后继承IpRateLimitMiddleware类,重写ReturnQuotaExceededResponse方法,代码如下:
public class IPLimitMiddleware : IpRateLimitMiddleware
{
private readonly IpRateLimitOptions _options;
private readonly IIpPolicyStore _ipPolicyStore;
public IPLimitMiddleware(RequestDelegate next, IOptions<IpRateLimitOptions> options, IRateLimitCounterStore counterStore, IIpPolicyStore policyStore,
IRateLimitConfiguration config, ILogger<IpRateLimitMiddleware> logger)
: base(next, options, counterStore, policyStore, config, logger)
{
_options = options.Value;
_ipPolicyStore = policyStore;
}
public override Task ReturnQuotaExceededResponse(HttpContext httpContext, RateLimitRule rule, string retryAfter)
{
var ip = httpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (string.IsNullOrEmpty(ip))
{
ip = httpContext.Connection.RemoteIpAddress.ToString();
}
httpContext.Response.ContentType = "application/json";
return httpContext.Response.WriteAsync($"{{ \"Code\": 429,\"msg\": \"操作频率过快,要求是: 每{rule.Period}秒{rule.Limit}次,请在{retryAfter}秒后再试!\" }}");
}
}
小问题1:在appsettings.json中定义的中文信息,取出来之后如果出现了乱码,则可以通过notpad++ 将文件格式改为utf-8
![](https://i-blog.csdnimg.cn/blog_migrate/c7d837e1f15919013c4f22492bd68d47.png)