Web API中常用Filter的执行顺序举例讲解

时间:2022-11-18 15:27:23

在WEB Api中,引入了面向切面编程(AOP)的思想,在某些特定的位置可以插入特定的Filter进行过程拦截处理。引入了这一机制可以更好地践行DRY(Don’t Repeat Yourself)思想,通过Filter能统一地对一些通用逻辑进行处理,如:权限校验、参数加解密、参数校验等方面我们都可以利用这一特性进行统一处理,今天我们来介绍Filter的开发、使用以及讨论他们的执行顺序。

1.Web中常用的Filter

Web api中最常用的filter有AuthorizeAttribute,ActionFilterAttribute,ExceptionFilterAttribute。AuthorizeAttribute主要用于权限的认证,ActionFilterAttribute用于action的处理,ExceptionFilterAttribute用于异常的处理

2.代码

/// <summary>
/// 监测数据类
/// </summary>
public class GlobalClass
{
public static string Message = "";
}
/// <summary>
/// action过滤器
/// </summary>
public class TestActionFilterAttribute: ActionFilterAttribute
{
/// <summary>
/// 执行后
/// </summary>
/// <param name="actionExecutedContext"></param>
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
GlobalClass.Message = GlobalClass.Message + " OnActionExecuted;";
} /// <summary>
/// 执行前
/// </summary>
/// <param name="actionContext"></param>
public override void OnActionExecuting(HttpActionContext actionContext) {
GlobalClass.Message = GlobalClass.Message + " OnActionExecuting;";
}
}
/// <summary>
/// 授权过滤器
/// </summary>
public class TestAuthorizeAttribute: AuthorizeAttribute
{
/// <summary>
/// 授权方法
/// </summary>
/// <param name="actionContext"></param>
public override void OnAuthorization(HttpActionContext actionContext)
{
GlobalClass.Message = GlobalClass.Message + " OnAuthorization;";
}
}
/// <summary>
/// 异常处理
/// </summary>
public class TestExceptionFilterAttribute : ExceptionFilterAttribute
{
/// <summary>
/// 异常处理
/// </summary>
/// <param name="actionExecutedContext"></param>
public override void OnException(HttpActionExecutedContext actionExecutedContext) {
GlobalClass.Message = GlobalClass.Message + " OnException;";
actionExecutedContext.Response = new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(GlobalClass.Message, Encoding.UTF8, "application/json"),
};
}
}
public class ValuesController : ApiController
{
public ValuesController() {
GlobalClass.Message = "";
GlobalClass.Message = GlobalClass.Message + " ValuesController;";
} [TestActionFilter]
[TestExceptionFilter]
[TestAuthorize]
public string Get(int id)
{
GlobalClass.Message = GlobalClass.Message + " Get;";
int.Parse("asdf");//测试异常
return GlobalClass.Message;
}
}

3.执行结果

Web API中常用Filter的执行顺序举例讲解

4.总结

由此可以看出Web api的执行顺序,构造函数 》AuthorizeAttribute 》ActionFilterAttribute 》ExceptionFilterAttribute

AuthorizationFilter的执行是ActionInvoker进行Action执行的第一项工作,因为后续的工作(Model绑定、Model验证、Action方法执行等)只有在成功授权的基础上才会有意义。