コード例 #1
0
    // TODO - EventSource?
    /// <summary>
    /// Invokes the logic of the middleware.
    /// </summary>
    /// <param name="context">The <see cref="HttpContext"/>.</param>
    /// <returns>A <see cref="Task"/> that completes when the request leaves.</returns>
    public async Task Invoke(HttpContext context)
    {
        using var lease = await TryAcquireAsync(context);

        if (lease.IsAcquired)
        {
            await _next(context);
        }
        else
        {
            RateLimiterLog.RequestRejectedLimitsExceeded(_logger);
            // OnRejected "wins" over DefaultRejectionStatusCode - we set DefaultRejectionStatusCode first,
            // then call OnRejected in case it wants to do any further modification of the status code.
            context.Response.StatusCode = _rejectionStatusCode;
            await _onRejected(context, lease);
        }
    }
コード例 #2
0
    private async Task InvokeInternal(HttpContext context, EnableRateLimitingAttribute?enableRateLimitingAttribute)
    {
        using var leaseContext = await TryAcquireAsync(context);

        if (leaseContext.Lease.IsAcquired)
        {
            await _next(context);
        }
        else
        {
            var thisRequestOnRejected = _defaultOnRejected;
            RateLimiterLog.RequestRejectedLimitsExceeded(_logger);
            // OnRejected "wins" over DefaultRejectionStatusCode - we set DefaultRejectionStatusCode first,
            // then call OnRejected in case it wants to do any further modification of the status code.
            context.Response.StatusCode = _rejectionStatusCode;

            // If this request was rejected by the endpoint limiter, use its OnRejected if available.
            if (leaseContext.GlobalRejected == false)
            {
                DefaultRateLimiterPolicy?policy;
                // Use custom policy OnRejected if available, else use OnRejected from the Options if available.
                policy = enableRateLimitingAttribute?.Policy;
                if (policy is not null)
                {
                    thisRequestOnRejected = policy.OnRejected;
                }
                else
                {
                    var policyName = enableRateLimitingAttribute?.PolicyName;
                    if (policyName is not null && _policyMap.TryGetValue(policyName, out policy) && policy.OnRejected is not null)
                    {
                        thisRequestOnRejected = policy.OnRejected;
                    }
                }
            }
            if (thisRequestOnRejected is not null)
            {
                await thisRequestOnRejected(new OnRejectedContext()
                {
                    HttpContext = context, Lease = leaseContext.Lease
                }, context.RequestAborted);
            }
        }
    }