1,直接上代码
public class RequestThrottlingMiddleware
{
private const int outtime = 10;
private const int total = 100;
private readonly RequestDelegate _next;
private readonly IMemoryCache _cache;
public RequestThrottlingMiddleware(RequestDelegate next, IMemoryCache cache)
{
_next = next;
_cache = cache;
}
public async Task Invoke(HttpContext context)
{
var ipAddress = context.Connection.RemoteIpAddress.ToString();
var timeWindow = TimeSpan.FromSeconds(outtime);
var cacheKey = $"{ipAddress}_{DateTime.UtcNow.Ticks / timeWindow.Ticks}";
if (_cache.TryGetValue(cacheKey, out int requestCount))
{
if (requestCount > total)
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("IP Address is blacklisted.请求太频繁了,休息一下发请求吧!");
}
else
{
_cache.Set(cacheKey, requestCount + 1, timeWindow);
await _next(context);
}
}
else
{
_cache.Set(cacheKey, 1, timeWindow);
await _next(context);
}
}
}
2, 配置中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
app.UseMiddleware<RequestThrottlingMiddleware>();
}