最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How to Identify the Rejected PolicyName When Handling 429 Rate Limit Errors in .Net? - Stack Overflow

programmeradmin2浏览0评论

I am using multiple rate-limiting policies in my .NET application, and I want to determine which specific policy caused a request to be rejected (HTTP 429). This is important for logging and metrics purposes.

I have defined multiple policies using RateLimitPartition.GetFixedWindowLimiter as follows:

limiterOptions.AddPolicy("InternalServicePolicy", httpContext =>
{
    return RateLimitPartition.GetFixedWindowLimiter("InternalServicePolicy",
        _ => new FixedWindowRateLimiterOptions()
        {
            PermitLimit = rateLimitingOptions.InternalServicePolicyOptions.PermitLimit,
            Window = TimeSpan.FromSeconds(rateLimitingOptions.InternalServicePolicyOptions.TimePeriod),
            AutoReplenishment = true,
            QueueLimit = 0,
        });
});

limiterOptions.AddPolicy("ThirdPartyPolicy", httpContext =>
{
    return RateLimitPartition.GetFixedWindowLimiter("ThirdPartyPolicy",
        _ => new FixedWindowRateLimiterOptions()
        {
            PermitLimit = rateLimitingOptions.ThirdPartyPolicyOptions.PermitLimit,
            Window = TimeSpan.FromSeconds(rateLimitingOptions.ThirdPartyPolicyOptions.TimePeriod),
            AutoReplenishment = true,
            QueueLimit = 0,
        });
});

limiterOptions.OnRejected = async (context, cancellationToken) =>
{
    // Metrics and logging

    context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
    await context.HttpContext.Response.WriteAsync(
       "Too many requests. Please try again later. " +
        "Read more about our rate limits at .", cancellationToken: cancellationToken);
};

I am using multiple rate-limiting policies in my .NET application, and I want to determine which specific policy caused a request to be rejected (HTTP 429). This is important for logging and metrics purposes.

I have defined multiple policies using RateLimitPartition.GetFixedWindowLimiter as follows:

limiterOptions.AddPolicy("InternalServicePolicy", httpContext =>
{
    return RateLimitPartition.GetFixedWindowLimiter("InternalServicePolicy",
        _ => new FixedWindowRateLimiterOptions()
        {
            PermitLimit = rateLimitingOptions.InternalServicePolicyOptions.PermitLimit,
            Window = TimeSpan.FromSeconds(rateLimitingOptions.InternalServicePolicyOptions.TimePeriod),
            AutoReplenishment = true,
            QueueLimit = 0,
        });
});

limiterOptions.AddPolicy("ThirdPartyPolicy", httpContext =>
{
    return RateLimitPartition.GetFixedWindowLimiter("ThirdPartyPolicy",
        _ => new FixedWindowRateLimiterOptions()
        {
            PermitLimit = rateLimitingOptions.ThirdPartyPolicyOptions.PermitLimit,
            Window = TimeSpan.FromSeconds(rateLimitingOptions.ThirdPartyPolicyOptions.TimePeriod),
            AutoReplenishment = true,
            QueueLimit = 0,
        });
});

limiterOptions.OnRejected = async (context, cancellationToken) =>
{
    // Metrics and logging

    context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
    await context.HttpContext.Response.WriteAsync(
       "Too many requests. Please try again later. " +
        "Read more about our rate limits at https://example.org/docs/ratelimiting.", cancellationToken: cancellationToken);
};
Share Improve this question edited yesterday DavidG 119k13 gold badges228 silver badges234 bronze badges asked yesterday Navid ZareNavid Zare 331 silver badge4 bronze badges New contributor Navid Zare is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 2
  • 1 Does context.Lease on the OnRejected callback have something you can use? – DavidG Commented yesterday
  • 1 @DavidG is on the right track, though I'm surprised there isn't a standard code example that details this. In other implementations on a 429 response there will be additional headers that detail the different counters for the policies that we enabled – Chris Schaller Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 1

The easiest way is to rely on the endpoint metadata:

limiterOptions.OnRejected = async (context, cancellationToken) =>
{
    // Metrics and logging

    // policyName from metadata
    var policyName = context.HttpContext
    .GetEndpoint()
    .Metadata
    .GetMetadata<EnableRateLimitingAttribute>()
    .PolicyName;

    context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
    await context.HttpContext.Response.WriteAsync(
       "Too many requests. Please try again later. " +
        "Read more about our rate limits at https://example.org/docs/ratelimiting.", cancellationToken: cancellationToken);
};
发布评论

评论列表(0)

  1. 暂无评论