我正在每个固定窗口实施 ASP.NET Core 速率限制:
builder.Services.AddRateLimiter(options =>
{
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
{
var remoteIpAddress = httpContext.Connection.RemoteIpAddress;
var localIpAddress = httpContext.Connection.LocalIpAddress;
var partitionKey = $"{remoteIpAddress} {localIpAddress}";
return RateLimitPartition.GetFixedWindowLimiter(partitionKey, options => new FixedWindowRateLimiterOptions
{
AutoReplenishment = true,
PermitLimit = 10,
QueueLimit = 0,
Window = TimeSpan.FromMinutes(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst
});
});
options.OnRejected = async (context, cancellationToken) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
context.HttpContext.Response.Headers.RetryAfter = ((int)retryAfter.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo);
}
context.HttpContext.Response.Redirect("/RateLimitExceeded", false);
};
});
如你所见,我想重定向到某个URL,在本例中,它是一个Razor页面,当然,我不希望它参与速率限制过程,所以我添加了一个
[DisableRateLimiting]
模型属性:
[DisableRateLimiting]
public class RateLimitExceededModel : PageModel
{
public void OnGet() { }
}
但是,尽我所能,我无法让这太工作,这意味着,当达到限制时,我总是收到
ERR_TOO_MANY_REDIRECTS
错误,这意味着我以某种方式进入了重定向循环。
我怎样才能做到这一点,即重定向到不受速率限制的自定义页面?