一、在Model层添加一个类MyActionFilterAttribute.cs
//AllowMultiple = true:允许多个标签同时都起作用 [AttributeUsage(AttributeTargets.All,AllowMultiple = true)] public class MyActionFilterAttribute : ActionFilterAttribute { public string Name { get; set; } //Action执行之前先执行此方法 public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); //HttpContext.Current.Session[""] HttpContext.Current.Response.Write("<br />OnActionExecuting Action执行之前先执行此方法 :" + Name); } //Action执行之后 public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); HttpContext.Current.Response.Write("<br />OnActionExecuted Action执行之后:" + Name); } //ActionResult执行之前先执行此方法 public override void OnResultExecuting(ResultExecutingContext filterContext) { base.OnResultExecuting(filterContext); HttpContext.Current.Response.Write("<br />OnResultExecuting ActionResult执行之前先执行此方法:" + Name); } //ActionResult执行之后 public override void OnResultExecuted(ResultExecutedContext filterContext) { base.OnResultExecuted(filterContext); HttpContext.Current.Response.Write("<br />OnResultExecuted ActionResult执行之后:" + Name); } }
二、控制器调用:
[MyActionFilter(Name = "HomeController")] public class HomeController : Controller { [MyActionFilter(Name = "Index Action")] public ActionResult Index() { Response.Write("<p>Action执行了</p>"); return Content("<br />ok:视图被渲染<br />"); } }
三、异常时执行的方法,在Model添加一个类MyExceptionFilterAttribute.cs
public class MyExceptionFilterAttribute: HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); //当出现了异常的时候,才执行此方法 //记录日志 //多个线程同时访问一个日志文件 //性能非得低。 //考虑使用内存队列提高性能,Redis //加入观察者模式屏蔽写入不同地方的变化点 //log4net //页面跳转到错误页面或者是首页 HttpContext.Current.Response.Redirect("/Home/Index"); } }