求助:在Entity Framework Core 2.2版本API中实现AspNetCoreRateLimit
在Entity Framework Core 2.2 API中实现AspNetCoreRateLimit
1. 安装兼容的NuGet包
.NET Core 2.2仅兼容AspNetCoreRateLimit的2.x版本,3.x及以上版本仅支持.NET Core 3.0+,请勿安装高版本。执行以下命令安装对应版本:
Install-Package AspNetCoreRateLimit -Version 2.2.0
2. 修复服务注册缺失问题
.NET Core 2.2中限流服务的注册方式与高版本不同,以下是完整配置流程:
2.1 注册内存缓存与限流核心服务
在Startup.cs的ConfigureServices方法中,按顺序注册相关服务:
using AspNetCoreRateLimit; public void ConfigureServices(IServiceCollection services) { // 注册内存缓存,用于存储限流计数器 services.AddMemoryCache(); // 从配置文件加载限流规则 services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting")); services.Configure<IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies")); // 注册限流核心存储与配置服务 services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>(); services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); // 使用默认配置,若需自定义则替换为你的CustomRateLimitConfiguration services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>(); // 注册EF Core与MVC服务 services.AddDbContext<YourDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
2.2 配置限流中间件
在Configure方法中添加限流中间件(需放在路由中间件之前):
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } // 启用IP限流中间件 app.UseIpRateLimiting(); app.UseHttpsRedirection(); app.UseMvc(); }
3. 添加配置文件规则
在appsettings.json中添加限流规则示例:
{ "IpRateLimiting": { "EnableEndpointRateLimiting": true, "StackBlockedRequests": false, "HttpStatusCode": 429, "GeneralRules": [ { "Endpoint": "*", "Period": "1m", "Limit": 100 } ] } }
关键问题说明
- 找不到
AddInMemoryRateLimiting():该扩展方法是AspNetCoreRateLimit3.0+版本新增的,2.x版本需手动注册MemoryCacheIpPolicyStore和MemoryCacheRateLimitCounterStore替代。 - 找不到
IRateLimitConfiguration:确认已安装正确版本的NuGet包,并引用AspNetCoreRateLimit命名空间;自定义配置类需继承RateLimitConfiguration实现逻辑。
内容的提问来源于stack exchange,提问作者David Ruiz
相关产品推荐
相关产品推荐

