IP速率限制API的Json数据类型响应

时间:2019-03-05 18:18:57

标签: asp.net asp.net-core-2.0

https://github.com/stefanprodan/AspNetCoreRateLimit 我正在将此中间件用于asp.net core 2 rest api应用程序的速率限制。但问题是此库返回html响应。但是我需要json响应来解决我的问题

2 个答案:

答案 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.
     

您可以通过更改以下选项HttpStatusCodeQuotaExceededMessage来自定义响应, 如果您想实现自己的响应,可以覆盖IpRateLimitMiddleware.ReturnQuotaExceededResponse Retry-After标头值以秒表示。 (强调我的)