限流过滤器
public class RateLimitActionFilter : IAsyncActionFilter
{
private IMemoryCache MemoryCache { get; init; }
public RateLimitActionFilter(IMemoryCache memoryCache)
{
MemoryCache = memoryCache;
}
async Task IAsyncActionFilter.OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
IPAddress? addr = context.HttpContext.Connection.RemoteIpAddress;
string ip = context.HttpContext.Connection.Id;
if (addr != null)
ip = addr.ToString();
string key = $"visit_{ip}";
long? lastVisit = MemoryCache.Get<long?>(key);
if (lastVisit == null || Environment.TickCount64 - lastVisit > 1000)
{
MemoryCache.Set(key, Environment.TickCount64, TimeSpan.FromSeconds(10));
await next();
}
else
{
context.Result = new ObjectResult("too much access") { StatusCode = 429 };
}
}
}
注入asp.net core
builder.Services.AddMemoryCache();
builder.Services.Configure<MvcOptions>(opt =>
{
opt.Filters.Add<RateLimitActionFilter>();
opt.Filters.Add<MyExceptionFilter>();
opt.Filters.Add<MyActionFilter>();
opt.Filters.Add<TransactionScopeFilter>();
});
---------------------------
知道的更多,不知道的也更多
---------------------------