ASP.NET Core :中间件系列(三):中间件限流
中间件
微软官网定义: 中间件
中间件意思就是处理请求和响应的软件:
1、选择是否将请求传递到管道中的下一个组件。
2、可在管道中的下一个组件前后执行工作。
对中间件类 必须 包括以下
具有类型为 RequestDelegate 的参数的公共构造函数。
名为 Invoke 或 InvokeAsync 的公共方法。
此方法必须:返回 Task。
接受类型 HttpContext 的第一个参数。
Use
Run
Demo
public class UserVerifyMiddleware
{
private readonly RequestDelegate _next;
private readonly IMemoryCache _memCache;
private readonly ILogger<UserVerifyMiddleware> _logger;
public UserVerifyMiddleware(RequestDelegate next
, ILogger<UserVerifyMiddleware> logger, IMemoryCache memCache)
{
_next = next;
_logger = logger;
_memCache = memCache;
}
public async Task Invoke(HttpContext context)
{
var request_ip = string.IsNullOrEmpty(context.Request.Headers["X-Real-IP"].ToString()) ? context.Connection.RemoteIpAddress.MapToIPv4().ToString() : context.Request.Headers["X-Real-IP"].ToString();
var request_ForwardIp = string.IsNullOrEmpty(context.Request.Headers["X-Forwarded-For"].ToString()) ? context.Connection.RemoteIpAddress.MapToIPv4().ToString() : context.Request.Headers["X-Forwarded-For"].ToString();
var Referer = context.Request.Headers["Referer"].ToString();
try
{
if (!string.IsNullOrWhiteSpace(_memCache.Get<long?>(request_ForwardIp).ToString()))
{
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json; charset=utf-8";
var data = JsonConvert.SerializeObject(new ResponseValue()
{
Code = 400,
ErrorMsg = "Illegal access. Your IP ({" + request_ip + "}) has been recorded, if any questions, please contact us."
});
await context.Response.WriteAsync(data);
}
else
{
_memCache.Set(request_ForwardIp, Environment.TickCount64, TimeSpan.FromSeconds(2));
await _next(context);
}
}
catch (Exception ex)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsync("你的请求太频繁了");
}
//
}
}
public static class UserVerifyMiddlewareExtensions
{
public static IApplicationBuilder UserVerifyMiddleware(this IApplicationBuilder builder)
{
//使用 IApplicationBuilder 公开中间件
return builder.UseMiddleware<UserVerifyMiddleware>();
}
}