stefanprodan / WebApiThrottle

ASP.NET Web API rate limiter for IIS and Owin hosting
MIT License
1.28k stars 275 forks source link

ThrottlingHandler doesn't save policy to policy repository when using custom repository #71

Closed RGKaizen closed 7 years ago

RGKaizen commented 7 years ago

Hi, I'm not 100% if this is a bug, but here's where I'm at. If I do:

            configuration.MessageHandlers.Add(new CustomThrottlingHandler
            {
                Policy = ThrottlePolicy.FromStore(new PolicyConfigurationProvider()),
                PolicyRepository = _NinjectManager.Kernel.Get<IPolicyRepository>()
            });

The policy is not saved in the PolicyRepository.

    public ThrottlingHandler(ThrottlePolicy policy, IPolicyRepository policyRepository, IThrottleRepository repository, IThrottleLogger logger, IIpAddressParser ipAddressParser = null)
    {
      ...
      this.policy = policy;
      this.policyRepository = policyRepository;
      if (policyRepository == null)
        return;
      policyRepository.Save(ThrottleManager.GetPolicyKey(), policy);
    }

I suspect that this constructor is not actually called in my case and so the policy is not stored in the repository. Later when the throttling core checks the repository for the policy, it doesn't find anything.

You can test this during runtime by calling:

            var policy = _PolicyRepository.FirstOrDefault(ThrottleManager.GetPolicyKey());

In my case, this is always null.

If the policy repository is not set in the constructor, the issue disappears. But so long as a custom repository is used, the policy doesn't seem to save in the repository.

Am I missing something?

stefanprodan commented 7 years ago

After you create you custom handler you need to call the save method before you add it to the message handlers. Here is an example.

RGKaizen commented 7 years ago

Excellent! Thank you Stefan.