3

使用AspNetCoreRateLimit实现IP请求频率限制

 3 years ago
source link: https://azhuge233.com/%e4%bd%bf%e7%94%a8aspnetcoreratelimit%e5%ae%9e%e7%8e%b0ip%e8%af%b7%e6%b1%82%e9%a2%91%e7%8e%87%e9%99%90%e5%88%b6/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

使用AspNetCoreRateLimit实现IP请求频率限制

在项目内使用NuGet添加AspNetCoreRateLimit包 编辑Startup.cs,DI组件,并启用中间件
//using ...
using AspNetCoreRateLimit;
public void ConfigureServices(IServiceCollection services) {
// ...
services.AddOptions();
services.AddMemoryCache();
services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
services.Configure<IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies"));
services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
// ...
app.UseIpRateLimiting(); //注意在UseMvc()前注册
app.UseMvc();
//using ...
using AspNetCoreRateLimit;

public void ConfigureServices(IServiceCollection services) {
    // ...
    services.AddOptions();
    services.AddMemoryCache();

    services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
    services.Configure<IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies"));

    services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
    services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
    // ...   
    app.UseIpRateLimiting(); //注意在UseMvc()前注册

    app.UseMvc();
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK