ASP.NET Core WebApi 限流中间件 AspNetCoreRateLimit 初级使用教程

AspNetCoreRateLimit使用

    • 作用
    • 安装,初始化
    • 配置文件
    • 参考
      • 字段说明

作用

限制某个接口的使用频率

安装,初始化

  • 新建ASP.NET Core WebApi 项目
  • Nuget AspNetCoreRateLimit
  • 在Startup.cs文件中修改为如下代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspNetCoreRateLimit;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;

namespace WebApplication1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            启用限流,需在UseMvc前面
            app.UseIpRateLimiting();

            //原始代码
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }


        public void ConfigureServices(IServiceCollection services)
        {
            //需要从appsettings.json加载配置
            services.AddOptions();

            //需要存储速率限制计数器和ip规则
            services.AddMemoryCache();

            //从appsetting.json加载常规配置
            services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));

            从appsetting.json加载ip规则
            services.Configure<IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies"));

            //注入计数器和规则存储
            services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
            services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

            //添加框架服务
            services.AddMvc();

            // https://github.com/aspnet/Hosting/issues/793
            // 默认情况下,未注册IHpptContextAccessor服务
            // clientId/clientIp解析器使用它
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            // 配置(解析器,计数器和生成器)
            services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

            services.AddControllers();
        }

    }
}

配置文件

appsettings.json文件代码如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",


  "IpRateLimiting": {
    "EnableEndpointRateLimiting": true,
    "StackBlockedRequests": false,
    "RealIpHeader": "X-Real-IP",
    "ClientIdHeader": "X-ClientId",
    "HttpStatusCode": 429,
    "QuotaExceededResponse": {
      "Content": "{{\"code\":429,\"msg\":\"访问过于频繁,请稍后重试\",\"data\":null}}",
      "ContentType": "application/json; charset=utf-8",
      "StatusCode": 429
    },
    "GeneralRules": [
      {
        "Endpoint": "*:/api/test/",
        "Period": "10s",
        "Limit": 2
      },
      {
        "Endpoint": "*:/api/values/",
        "Period": "1s",
        "Limit": 10
      }

    ]
  }
}

其中 QuotaExceededResponse 为自定义返回内容,可删除返回默认内容,此处返回中文乱码,原因未知

参考

GitHub作者原地址
GitHub定义速率限制规则
ASP.NET Core WebApi AspNetCoreRateLimit 限流中间件简单使用
使用AspNetCoreRateLimit实现IP请求频率限制
ASP.NET Core WebApi AspNetCoreRateLimit 限流中间件学习
.Net Core结合AspNetCoreRateLimit实现限流

字段说明

  • “EnableEndpointRateLimiting”: true, //false则全局将应用限制,并且仅应用具有作为端点的规则* 。 true则限制将应用于每个端点,如{HTTP_Verb}{PATH}
  • “StackBlockedRequests”: false,//false则拒绝的API调用不会添加到调用次数计数器上
  • “Endpoint” 接口地址
  • “Period” 期间(时间) 1s 1m 1h 1d 秒分时天
  • “Limit” 限制次数

你可能感兴趣的:(Web)