ApiProtector.Net添加多条防护规则时报错:已存在相同键X-API-Protector
问题原因
该报错是因为同一个接口端点上重复添加[ApiProtector]特性时,所有未显式指定RuleKey参数的特性都会使用默认键名X-API-Protector,导致内部配置存储时出现重复键冲突。
解决方案
可根据你的规则配置需求选择以下任意一种修复方式:
方式1:单特性合并同参数规则
如果多条防护规则的限流阈值、时间窗口、处罚时长参数完全一致,可以直接在同一个[ApiProtector]特性中传入多个防护类型,无需重复添加特性:
[ApiProtector(new []{ ApiProtectionType.ByIpAddress, ApiProtectionType.ByIdentity }, Limit: 10, TimeWindowSeconds: 10, PenaltySeconds: 60)]
方式2:为每个特性指定独立RuleKey
如果不同规则的配置参数存在差异,需要单独添加多个特性,只需给每个特性显式设置不重复的RuleKey参数即可:
[ApiProtector(ApiProtectionType.ByIpAddress, Limit: 10, TimeWindowSeconds: 10, PenaltySeconds: 60, RuleKey: "X-API-Protector-IP")] [ApiProtector(ApiProtectionType.ByIdentity, Limit: 10, TimeWindowSeconds: 10, PenaltySeconds: 60, RuleKey: "X-API-Protector-Identity")]
修改后重新编译运行即可解决重复键报错。
内容的提问来源于stack exchange,提问作者Alexei Sarmiento
相关产品推荐
相关产品推荐

