过滤器是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();
}
}