https://github.com/stefanprodan/AspNetCoreRateLimit 我正在将此中间件用于asp.net core 2 rest api应用程序的速率限制。但问题是此库返回html响应。但是我需要json响应来解决我的问题
答案 0 :(得分:1)
您可以在IpRateLimitMiddleware
中自定义响应。
IpRateLimitMiddleware
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);
var message = new { rule.Limit, rule.Period, retryAfter };
httpContext.Response.Headers["Retry-After"] = retryAfter;
httpContext.Response.StatusCode = 200;
httpContext.Response.ContentType = "application/json";
return httpContext.Response.WriteAsync(JsonConvert.SerializeObject(message));
}
}
在Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//app.UseIpRateLimiting();
app.UseMiddleware<MyIpRateLimitMiddleware>();
//your rest middlware
}
答案 1 :(得分:0)
阅读docs
如果请求被阻止,则客户端会收到如下文本响应:
Status Code: 429 Retry-After: 58 Content: API calls quota exceeded! maximum admitted 2 per 1m.
您可以通过更改以下选项
HttpStatusCode
和QuotaExceededMessage
来自定义响应, 如果您想实现自己的响应,可以覆盖IpRateLimitMiddleware.ReturnQuotaExceededResponse
。Retry-After
标头值以秒表示。 (强调我的)