protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var identifier = GetUserIdentifier(request);

            if (string.IsNullOrEmpty(identifier))
            {
                return(CreateResponse(request, HttpStatusCode.Forbidden, "Could not identify client."));
            }

            var maxRequests = _maxRequestsForUserIdentifier(identifier);

            ThrottleEntry entry = null;

            if (_store.TryGetValue(identifier, out entry))
            {
                if (entry.PeriodStart + _period < DateTime.UtcNow)
                {
                    _store.Rollover(identifier);
                }
            }
            _store.IncrementRequests(identifier);
            if (!_store.TryGetValue(identifier, out entry))
            {
                return(CreateResponse(request, HttpStatusCode.Forbidden, "Could not identify client."));
            }

            Task <HttpResponseMessage> response = null;

            if (entry.Requests > maxRequests)
            {
                response = CreateResponse(request, HttpStatusCode.ServiceUnavailable, _message);
            }
            else
            {
                response = base.SendAsync(request, cancellationToken);
            }

            return(response.ContinueWith(task =>
            {
                var remaining = maxRequests - entry.Requests;
                if (remaining < 0)
                {
                    remaining = 0;
                }

                var httpResponse = task.Result;
                httpResponse.Headers.Add("RateLimit-Limit", maxRequests.ToString());
                httpResponse.Headers.Add("RateLimit-Remaining", remaining.ToString());

                return httpResponse;
            }));
        }
Beispiel #2
0
 public bool TryGetValue(string key, out ThrottleEntry entry)
 {
     return(_throttleStore.TryGetValue(key, out entry));
 }
 public bool TryGetValue(string key, out ThrottleEntry entry)
 {
     return _throttleStore.TryGetValue(key, out entry);
 }