Exemplo n.º 1
0
        public async Task Invoke(HttpContext context)
        {
            var endpoint = context.GetEndpoint();

            var throttleMetadata = endpoint?.Metadata.GetMetadata <IThrottleMetadata>();

            if (throttleMetadata == null)
            {
                await _next.Invoke(context);

                return;
            }

            var disableThrottle = endpoint?.Metadata.GetMetadata <IDisableThrottle>();

            if (disableThrottle != null)
            {
                await _next.Invoke(context);

                return;
            }

            var policy = await _throttlePolicyProvider.GetPolicyAsync(throttleMetadata.PolicyName);

            if (policy == null)
            {
                context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                return;
            }

            if (policy.Resolver == null)
            {
                context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                return;
            }

            var scope = await policy.Resolver.ResolveAsync(context);

            var isSafe = await CheckSafeScopes(context, policy, scope);

            if (isSafe)
            {
                await _next.Invoke(context);

                return;
            }

            IReadOnlyList <ThrottleRule> generalRules;

            if (throttleMetadata is IThrottleRulesMetadata throttle)
            {
                // ThrottleRuleMetadata overrides the general rule
                generalRules = throttle.GeneralRules;
            }
            else
            {
                generalRules = policy.GeneralRules;
            }

            IReadOnlyList <ThrottleRule> specificRules;

            if (policy.SpecificRules.TryGetValue(scope, out var specificRulesList))
            {
                specificRules = specificRulesList;
            }
            else
            {
                specificRules = _emptyRules;
            }

            var rules = _throttlerService.GetRules(generalRules, specificRules);

            (ThrottleRule rule, Counter counter, bool hasBeenSet)longestRule = (default, default, false);