public void Throttle(IHttpRequest request, IHttpResponse response) { var resources = request.TryResolve <IResourceManager>(); ThrottlingConfiguration configuration = resources.Get(ThrottlingConfiguration.Key, ThrottlingConfiguration.Empty()); var key = ApiKey.ExtractFrom(request); if (!key.IsMissing && configuration.ThrottlingEnabled) { var repository = request.TryResolve <IRequestCountRepository>(); RequestCount count = repository.Ensure(key, () => new RequestCount(configuration.Period)); if (count.IsLessThan(configuration.NumberOfRequests)) { repository.Update(key, count.Increase()); } else { response.AddHeader("Retry-After", configuration.FormattedSeconds); throw new HttpError(429, configuration.ErrorMessage()); } } }
public void Rate(IHttpRequest request, IHttpResponse response) { ApiKey apiKey = ApiKey.ExtractFrom(request); if (!apiKey.IsMissing) { var resources = request.TryResolve <IResourceManager>(); ThrottlingConfiguration configuration = resources.Get(ThrottlingConfiguration.Key, ThrottlingConfiguration.Empty()); var repository = request.TryResolve <IRequestCountRepository>(); RequestCount count = repository.Get(apiKey); addLimitHeader(response, configuration); addRemainingHeader(response, configuration, count); addResetHeader(response, configuration, count); } }