.net mvc 中使用ActionFilterAttribute过滤器

过滤器是mvc中常用的
在.net mvc 中直接继承和实现ActionFilterAttribute类就可以了
很简单
下面贴出一个例子
过滤器:


public class UseStopwatchAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    filterContext.Controller.ViewData["stopWatch"] = stopWatch;
  }
  public override void OnResultExecuting(ResultExecutingContext filterContext)
  {
    Stopwatch stopWatch = (Stopwatch)filterContext.Controller.ViewData["stopWatch"];
    stopWatch.Stop();
    Random r = new Random();
    filterContext.Controller.ViewData["elapsedTime"] = stopWatch.ElapsedMilliseconds
    + " milliseconds -   Rand  " + r.Next(1000).ToString();
  }
}

这的话这个过滤器就写好了
在使用的时候只要在controller上写上就行了


[UseStopwatch]
public class ProductsController : Controller
{
  //
  // GET: /Store/Products/
  public ActionResult List()
  {
    return View();
  }
  public ActionResult Details()
  {
    return View();
  }
  public ActionResult AddReview()
  {
    return View();
  }
}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注