IPRateExtension.cs 1.1 KB

123456789101112131415161718192021222324
  1. using AspNetCoreRateLimit;
  2. namespace Extensions
  3. {
  4. public static class IPRateExtension
  5. {
  6. public static void AddIPRate(this IServiceCollection services, IConfiguration configuration)
  7. {
  8. if (services == null) throw new ArgumentNullException(nameof(services));
  9. //从appsettings.json中加载常规配置,IpRateLimiting与配置文件中节点对应
  10. services.Configure<IpRateLimitOptions>(configuration.GetSection("IpRateLimiting"));
  11. //从appsettings.json中加载Ip规则
  12. services.Configure<IpRateLimitPolicies>(configuration.GetSection("IpRateLimitPolicies"));
  13. //注入计数器和规则存储
  14. services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
  15. services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
  16. //配置(解析器、计数器密钥生成器)
  17. services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
  18. services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();
  19. }
  20. }
  21. }