关于c#:如何在-AspNet-Core-中对请求进行限流

7次阅读

共计 2580 个字符,预计需要花费 7 分钟才能阅读完成。

译文链接:https://www.infoworld.com/art…

在利用程序开发时,或者你有这样的想法,管制用户的申请频率来避免一些用户的歹意攻打,具体的说就是:为了预防有名的 拒绝服务 攻打,限度某一个 ip 在一段时间内的拜访次数,要解决这个问题,就要用到限流机制。

限流可能很好的管制住一个客户端拜访服务器资源地址的申请次数,在 asp.net core 之前,要实现限流机制,你可能要自定义 module 或者 handler,太繁琐了,不过很开心的是,在 asp.net core 里,能够很轻松的实现限流性能,这得益于 asp.net core 特有的 pipeline 机制,接下来,咱们一起钻研一下如何在 asp.net core 中实现限流机制。

装置 限流中间件

为了可能实现限流性能,能够应用第三方提供的限流中间件,利用这个中间件给多个场景进行限流,比方:容许某一个 ip 或者 ip 段 在指定的工夫周期内拜访某一个资源的次数,这个周期能够是:每秒,每分钟,每 n 分钟,等等。

在 Visual Studio 中创立好 ASP.NET Core API 之后,下一步就是装置 限流包 AspNetCoreRateLimit,你能够在 NuGet Package Manager 可视化工具上装置,也能够在 .NET CLI 命令行中装置,语句如下:


dotnet add package AspNetCoreRateLimit

如果想理解限流包 AspNetCoreRateLimit 的更多常识,参考 github:https://github.com/stefanprod…

配置 AspNetCoreRateLimit

当初 AspNetCoreRateLimit 曾经援用到咱们我的项目中了,接下来在 ConfigureServices 办法中追加如下代码,最终将申请追加到 request-response pipeline 管道中。


    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {services.AddMvc().SetCompatibilityVersion
                        (CompatibilityVersion.Version_2_2);
            services.AddOptions();
            services.AddMemoryCache();
            services.Configure<IpRateLimitOptions>
            (Configuration.GetSection("IpRateLimit"));
            services.AddSingleton<IIpPolicyStore,
            MemoryCacheIpPolicyStore>();
            services.AddSingleton<IRateLimitCounterStore,
            MemoryCacheRateLimitCounterStore>();
            services.AddSingleton<IRateLimitConfiguration,
            RateLimitConfiguration>();
            services.AddHttpContextAccessor();}
    }

下面代码 Configuration.GetSection("IpRateLimit") 须要留神一下,节点 IpRateLimit 的具体限流信息是配在 appsettings.json 中的。

接下来在 Configure 办法中应用限流中间件。


    public class Startup
    {
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {if (env.IsDevelopment())
            {app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseIpRateLimiting();

            app.UseAuthorization();

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

最初再来看一下 appsettings.json 文件,着重看一下 限流规定 是怎么配置的,能够看出一个限流规定是由 端点 + 周期 + 次数 3 个元素组成的,残缺的 appsettings.json 配置如下:


{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "IpRateLimit": {
    "EnableEndpointRateLimiting": true,
    "StackBlockedRequests": false,
    "RealIPHeader": "X-Real-IP",
    "ClientIdHeader": "X-ClientId",
    "HttpStatusCode": 429,
    "GeneralRules": [
      {
        "Endpoint": "*/weatherforecast",
        "Period": "1m",
        "Limit": 5
      }
    ]
  }
}

下面的限流规定能够确保:含有 “/api” 的 url 链接在任何分钟周期内最多有 5 次访问。

测试 AspNetCoreRateLimit

上面就能够按下 Ctrl + F5 把应用程序跑起来,默认状况下申请会拜访 ValueController 的 Get 办法,而后刷新页面 5 次,会看到页面呈现如下信息。

因为是演示目标,所以这里我配置成了 5 次,理论开发中,大家能够依据我的项目的具体情况来设置这个限流阈值,当然更灵便的做法就是将 限流次数 保留在 数据库 或者缓存中,这样能够在程序运行过程中动静的批改这个阈值,太强大了。

更多高质量干货:参见我的 GitHub: dotnetfly

正文完
 0