1、在appsetting.json中配置參數
"IpRateLimiting": { //false則全局將應用限制,並且僅應用具有作為端點的規則* 。 true則限制將應用於每個端點,如{HTTP_Verb}{PATH} "EnableEndpointRateLimiting": true, //false則拒絕的API調用不會添加到調用次數計數器上 "StackBlockedRequests": false, //注意這個配置,表示獲取用戶端的真實IP,我們的線上經過負載后是 X-Forwarded-For,而測試服務器沒有,所以是X-Real-IP "RealIpHeader": "X-Real-IP", "ClientIdHeader": "X-ClientId", "HttpStatusCode": 200, //設置返回狀態碼 //"QuotaExceededResponse": { // "Content": "{{\"code\":429,\"msg\":\"訪問過於頻繁,請稍后重試\",\"data\":null}}", // "ContentType": "application/json", // "StatusCode": 200 //},//返回提示信息 "IpWhitelist": [], //限制白名單,在名單中的IP,則無訪問權限 "EndpointWhitelist": [], "ClientWhitelist": [], "GeneralRules": [ { "Endpoint": "*", //對所有接口進行監控 "Period": "10s", "Limit": 5 } ] },
2、在program.cs中配置
#region 限流配置 //加載配置 builder.Services.AddOptions(); //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);//設置兼容性版本 builder.Services.AddMemoryCache(); //加載IpRateLimiting配置 builder.Services.Configure<IpRateLimitOptions>(configuration.GetSection("IpRateLimiting")); //注入計數器和規則存儲 builder.Services.AddSingleton<IIpPolicyStore, DistributedCacheIpPolicyStore>(); builder.Services.AddSingleton<IRateLimitCounterStore, DistributedCacheRateLimitCounterStore>(); //添加框架服務 builder.Services.AddMvc(); // clientId / clientIp解析器使用它。 builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); //配置(計數器密鑰生成器) builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>(); #endregion
3、新建一個IPLimitMiddleware類
public class IPLimitMiddleware : IpRateLimitMiddleware { private readonly IpRateLimitOptions _options; private readonly IIpPolicyStore _ipPolicyStore; public IPLimitMiddleware(RequestDelegate next,IProcessingStrategy strategy, IOptions<IpRateLimitOptions> options, IIpPolicyStore policyStore, IRateLimitConfiguration config, ILogger<IpRateLimitMiddleware> logger) : base(next, strategy, options, 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(); } //后面需要將IP添加到數據庫中進行監控,以便對非法IP進行限制 httpContext.Response.ContentType = "application/json"; return httpContext.Response.WriteAsync($"{{ \"code\": 429,\"msg\": \"訪問過於頻繁,請稍后重試\",\"data\":null }}"); //httpContext.Response.Headers.Append("Access-Control-Allow-Origin", "*"); //return base.ReturnQuotaExceededResponse(httpContext, rule, retryAfter); } }
這里不太好測試,就只貼代碼