需要从 AspNetCoreRateLimit 库中抛出自定义错误或异常

Need Custom error or exception thrown from AspNetCoreRateLimit library

我想抛出自定义错误。在 json 这样的格式中

{
 "message":"API calls quota exceeded! maximum admitted 2 per 1m.",
 "status": 429
}

目前我收到字符串格式错误。

我的Startup.cs

if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/error");
            //app.UseMiddleware<RateLimitException>();
        }

        //add the IP rate limiting middleware to the HTTP request-response pipeline.
        app.UseIpRateLimiting();  

正如 document 所说:

You can customize the response by changing these options HttpStatusCode and QuotaExceededMessage, if you want to implement your own response you can override the IpRateLimitMiddleware.ReturnQuotaExceededResponse. The Retry-After header value is expressed in seconds.

那么,您可以参考this link.

的以下解决方案

使用以下代码创建一个 MyIPRateLimitMiddleware:

public class MyIPRateLimitMiddleware : IpRateLimitMiddleware
    {
        public MyIPRateLimitMiddleware(RequestDelegate next, IOptions<IpRateLimitOptions> options, IRateLimitCounterStore counterStore, IIpPolicyStore policyStore, IRateLimitConfiguration config, ILogger<IpRateLimitMiddleware> logger) : base(next, options, counterStore, policyStore, config, logger)
        {
        }

        public override Task ReturnQuotaExceededResponse(HttpContext httpContext, RateLimitRule rule, string retryAfter)
        {
          //  return base.ReturnQuotaExceededResponse(httpContext, rule, retryAfter);
            string str = string.Format("API calls quata exceeded! maximum maximum admitted {0} per {1}", rule.Limit,
                rule.Period);
            var result = JsonConvert.SerializeObject(new {error = str});
            httpContext.Response.Headers["Retry-After"] = retryAfter;
            httpContext.Response.StatusCode = 429;
            httpContext.Response.ContentType = "application/json";

            return httpContext.Response.WriteAsync(result);
        }
    }

然后在Startup.Configure方法中,去掉app.UseIpRateLimiting();,在任何中间件前添加如下代码

app.UseMiddleware<MyIPRateLimitMiddleware>();

此外,您也可以尝试设置QuotaExceededResponse配置

"IpRateLimiting": {
        "......":"......",
        "QuotaExceededResponse": {
            "ContentType": "application/json",
            "Content": "{{\"error\":\"API calls quota exceeded! maximum admitted {0} per {1}.\"}}"
        }
    }

参考:Rest api json response and Configurable ReturnQuotaExceededResponse content.