AspNetCoreRateLimit接口訪問限制中間件的使用


1、在接口項目nutget中找到AspNetCoreRateLimit組件

    

 

 2、在appsettings.json中配置以下內容

     

 

 

"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方法中添加配置

            #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方法中注冊使用中間件

    

 

 

   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

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM