首页 > 解决方案 > apiprotector.net 错误 已添加具有相同密钥的项目。密钥:X-API-保护器

问题描述

ApiProtector.Net ( https://apiprotector.net/ ),给我错误:已添加具有相同键的元素。关键:X-API-Protector,当我使用多个规则保护端点时。

[ApiProtector(ApiProtectionType.ByIpAddress, Limit: 10, TimeWindowSeconds: 10, PenaltySeconds: 60)]
[ApiProtector(ApiProtectionType.ByIdentity, Limit: 10, TimeWindowSeconds: 10, PenaltySeconds: 60)]

标签: c#.net.net-5

解决方案


我发现解决方案是 ApiProtector.Net 中的一个错误。尝试在 hader 中多次添加密钥:X-API-Protector

创建一个继承自 ApiProtector 的类,并覆盖 OnActionExecuted 方法。

public class CustomApiProtector : ApiProtector
{
    public CustomApiProtector(ApiProtectionType type, uint limit, uint timeWindowSeconds, uint penaltySeconds ):base(type, limit, timeWindowsSecond, penaltySeconds)
    {

    }

    public override void OnActionExecuted(ActionExecutedContext context)
    {

        base.OnActionExecuted(context);


        IHeaderDictionary headers = context.HttpContext.Response.Headers;
        StringValues locationHeaderValue = string.Empty;
        if (headers.TryGetValue("X-API-Protector", out locationHeaderValue))
        {
            context.HttpContext.Response.Headers.Remove("X-API-Protector");
            
        }

      
    }

}

推荐阅读