ASP.NET MVC ActionFilter自定义过滤器异常过滤器过滤器用法
自定义过滤器使用非常灵活,可以精确的注入到请求前、请求中和请求后。继承抽象类ActionFilterAttribute并重写里面的方法即可:
public class SystemLogAttribute : ActionFilterAttribute
{
public string Operate { get; set; }
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.HttpContext.Response.Write("<br/>" + Operate + ":OnActionExecuted");
base.OnActionExecuted(filterContext);
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.Write("<br/>" + Operate + ":OnActionExecuting");
base.OnActionExecuting(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.Write("<br/>" + Operate + ":OnResultExecuted");
base.OnResultExecuted(filterContext);
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Write("<br/>" + Operate + ":OnResultExecuting");
base.OnResultExecuting(filterContext);
}
}
这个过滤器适合做系统操作日志记录功能:
[SystemLog(Operate = "添加用户")]
public string CustomerFilterTest()
{
Response.Write("<br/>Action 执行中...");
return "<br/>Action 执行结束";
}
看下结果:
四个方法执行顺序:OnActionExecuting—>OnActionExecuted—>OnResultExecuting—>OnResultExecuted,非常精确的控制了整个请求过程。
实际开发中中记录日志过程是这样的:在OnActionExecuting方法里写一条操作日志到数据库里,全局变量存下这条记录的主键,到OnResultExecuted方法里说明请求结束了,这个时候自然知道用户的这个操作是否成功了,根据主键更新下这条操作日志的是否成功字段。