译文连接: https://www.infoworld.com/art...
在应用程序开发时,或许你有这样的想法,控制用户的请求频率来防止一些用户的恶意攻击,具体的说就是:为了预防有名的 拒绝服务 攻击,限制某一个ip在一段时间内的访问次数,要解决这个问题,就要用到限流机制。html
限流可以很好的控制住一个客户端访问服务器资源地址的请求次数,在 asp.net core 以前,要实现限流机制,你可能要自定义 module 或者 handler,太繁琐了,不过很开心的是,在 asp.net core 里,能够很轻松的实现限流功能,这得益于 asp.net core 特有的 pipeline 机制,接下来,咱们一块儿研究一下如何在 asp.net core 中实现限流机制。git
为了可以实现限流功能,可使用第三方提供的限流中间件,利用这个中间件给多个场景进行限流,好比:容许某一个 ip 或者 ip段 在指定的时间周期内访问某一个资源的次数,这个周期能够是:每秒,每分钟,每 n 分钟,等等。github
在 Visual Studio 中建立好 ASP.NET Core API 以后,下一步就是安装 限流包 AspNetCoreRateLimit
,你能够在 NuGet Package Manager
可视化工具上安装,也能够在 .NET CLI 命令行中安装,语句以下:数据库
dotnet add package AspNetCoreRateLimit
若是想了解限流包 AspNetCoreRateLimit 的更多知识,参考 github: https://github.com/stefanprod...json
如今 AspNetCoreRateLimit 已经引用到咱们项目中了,接下来在 ConfigureServices 方法中追加以下代码,最终将请求追加到 request-response pipeline
管道中。api
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 配置以下:app
{ "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次访问。asp.net
下面就能够按下 Ctrl + F5 把应用程序跑起来,默认状况下请求会访问 ValueController 的 Get 方法,而后刷新页面5次,会看到页面出现以下信息。
由于是演示目的,因此这里我配置成了5次,实际开发中,你们能够根据项目的具体状况来设置这个限流阈值,固然更灵活的作法就是将 限流次数 保存在 数据库 或者缓存中,这样能够在程序运行过程当中动态的修改这个阈值,太强大了。
更多高质量干货:参见个人 GitHub: dotnetfly