- 权限验证过滤器
public class AuthFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
var authorize = context.HttpContext.Request.Headers["token"];
if (string.IsNullOrWhiteSpace(authorize))
{
context.Result = new JsonResult(new { code = 500, message = "token不能为空" });
return;
}
}
}
- 程序异常过滤器
public class ExceptionFilter : IAsyncExceptionFilter
{
private readonly IWebHostEnvironment _environment;
public ExceptionFilter(IWebHostEnvironment environment)
{
this._environment = environment;
}
public Task OnExceptionAsync(ExceptionContext context)
{
string msg;
if (_environment.EnvironmentName == "Development")
{
msg = context.Exception.ToString();
}
else
{
msg = "服务器发生未处理异常";
}
JsonResult result = new JsonResult(new { code = 500, message = msg });
context.Result = result;
context.ExceptionHandled = true;
return Task.CompletedTask;
}
}
- 模型验证过滤器
public class ModelValidateFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var errors = context.ModelState
.Where(e => e.Value.Errors.Count > 0)
.Select(e => e.Value.Errors.First().ErrorMessage)
.ToList();
var str = string.Join("|", errors);
JsonResult result = new JsonResult(new
{
Code = 10000,
Msg = $"数据验证:{str}"
});
context.Result = result;
}
}
}
- 限流过滤器
public class RateLimitFilter : IAsyncActionFilter
{
private readonly IMemoryCache memCache;
public RateLimitFilter(IMemoryCache memCache)
{
this.memCache = memCache;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
string ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
string cacheKey = $"lastvisittick_{ip}";
long? lastVisit = memCache.Get<long?>(cacheKey);
if (lastVisit == null || Environment.TickCount64 - lastVisit > 200)
{
memCache.Set(cacheKey, Environment.TickCount64, TimeSpan.FromSeconds(10));
await next();
}
else
{
JsonResult result = new JsonResult(new
{
Code = 429,
Msg = "您的,手速太快,访问太频繁了!"
});
context.Result = result;
}
}
}