本文主要是介绍asp.net core 限流filter,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
限流过滤器
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>();
});
这篇关于asp.net core 限流filter的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!