标签:过滤器
<1>
MyActionFilterAttribute.cs类
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApp.Models { //ActionFilterAttribute这个类是继承了FilterAttribute类, 和IActionFilter, IResultFilter这两个接口的,就表名这个ActionFilterAttribute抽象类既是Action的过滤器,也是一个视图结果的过滤器(它下面有四个虚方法供我们重写) public class MyActionFilterAttribute:ActionFilterAttribute { public string ActionName { get; set; } //Action执行之前先执行此方法 public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); HttpContext.Current.Response.Write("</br>OnActionExecuting---我在" + ActionName + "方法之前执行"); } //Action执行之后执行此方法 public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); HttpContext.Current.Response.Write("</br>OnActionExecuted---我在" + ActionName + "方法之后执行</br>"); } //视图(ActionResult)执行之前,执行此方法 public override void OnResultExecuting(ResultExecutingContext filterContext) { base.OnResultExecuting(filterContext); HttpContext.Current.Response.Write("</br>OnResultExecuting---我在" + ActionName+"方法的视图执行之前执行"); } //视图(ActionRetult)执行之后,执行此方法 public override void OnResultExecuted(ResultExecutedContext filterContext) { base.OnResultExecuted(filterContext); HttpContext.Current.Response.Write("</br>OnResultExecuted---我在" + ActionName+"方法的视图执行之后执行"); } } }
using MvcApp.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApp.Controllers { public class TestController : Controller { // // GET: /Test/ [MyActionFilter(ActionName = "Index")] public ActionResult Index() { Response.Write("<p style='color:Red' >Action方法被执行了</p>"); return Content("<p style='color:Red' >OK 视图被渲染</p>"); } } }执行http://localhost:10577/Test/Index方法输出结果如下:
标签:过滤器
原文地址:http://blog.csdn.net/fanbin168/article/details/43636245