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

Json data type response of IP rate limit API

我正在使用 AspNetCoreRateLimit 提供的中间件来对 ASP.NET Core 2.x REST API Web 应用程序的传入请求进行速率限制。

目前这个库 returns html 响应被拒绝的请求。我怎样才能让它变成 return json 响应?

阅读docs

If the request gets blocked then the client receives a text response like this:

Status Code: 429
Retry-After: 58
Content: API calls quota exceeded! maximum admitted 2 per 1m.

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. (emphasis mine)

您可以在 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
    }