天天看点

WebApi过滤器

  1. 权限验证过滤器
/// <summary>
/// 权限验证过滤器
/// </summary>
public class AuthFilter : IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        //if (context.Filters.Contains(new MyNoAuthentication()))
        //{
        //    return;
        //}
        var authorize = context.HttpContext.Request.Headers["token"];
        if (string.IsNullOrWhiteSpace(authorize))
        {
            context.Result = new JsonResult(new { code = 500, message = "token不能为空" });
            return;
        }
        //if (!MemoryCacheHelper.Exists(authorize))
        //{
        //    context.Result = new JsonResult("无效的授权信息或授权信息已过期");
        //    return;
        //}
    }
}
           
  1. 程序异常过滤器
/// <summary>
/// 程序异常过滤器
/// </summary>
public class ExceptionFilter : IAsyncExceptionFilter
{
    private readonly IWebHostEnvironment _environment;
    public ExceptionFilter(IWebHostEnvironment environment)
    {
        this._environment = environment;
    }

    public Task OnExceptionAsync(ExceptionContext context)
    {
        //context.Exception代表异常信息对象
        //如果给 context.ExceptionHandled赋值为true,则其他ExceptionFilter不会被执行
        //context.Result的值会被输出到客户端

        string msg;
        if (_environment.EnvironmentName == "Development")
        {
            msg = context.Exception.ToString();
        }
        else
        {
            msg = "服务器发生未处理异常";
        }
        //可以加log 输出
        JsonResult result = new JsonResult(new { code = 500, message = msg });
        context.Result = result;    //context.Result的值会被输出到客户端
        context.ExceptionHandled = true;  //其他ExceptionFilter不会被执行
        return Task.CompletedTask;
    }
}
           
  1. 模型验证过滤器
/// <summary>
/// 模型验证过滤器
/// </summary>
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;
        }
    }
}
           
  1. 限流过滤器
/// <summary>
/// 限流过滤器
/// </summary>
public class RateLimitFilter : IAsyncActionFilter
{
    private readonly IMemoryCache memCache;

    public RateLimitFilter(IMemoryCache memCache)
    {
        this.memCache = memCache;
    }

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        //Console.WriteLine("RateLimitActionFilter 执行action前");
        string ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
        string cacheKey = $"lastvisittick_{ip}";
        long? lastVisit = memCache.Get<long?>(cacheKey);
        if (lastVisit == null || Environment.TickCount64 - lastVisit > 200) // Environment.TickCount64 系统时间
        {
            memCache.Set(cacheKey, Environment.TickCount64, TimeSpan.FromSeconds(10));//避免长期不访问的用户,占据缓存的内存
            await next();
            //Console.WriteLine("RateLimitActionFilter 执行action后");
        }
        else
        {
            JsonResult result = new JsonResult(new
            {
                Code = 429,
                Msg = "您的,手速太快,访问太频繁了!"
             });
            context.Result = result;
        }
    }
}