我们先建立 一个Filter,名字叫做TestFilter
public class TestFilter : ActionFilterAttribute
{ public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.HttpContext.Session["temp"] += "TestFilter OnActionExecuting<br/>"; } public override void OnActionExecuted(ActionExecutedContext filterContext) { filterContext.HttpContext.Session["temp"] += "TestFilter OnActionExecuted<br/>"; } public override void OnResultExecuting(ResultExecutingContext filterContext) { filterContext.HttpContext.Session["temp"] += "TestFilter OnResultExecuting<br/>"; } public override void OnResultExecuted(ResultExecutedContext filterContext) { filterContext.HttpContext.Session["temp"] += "TestFilter OnResultExecuted<br/>"; } }一、应用于Action的Filter
[TestFilter]//将此Filter应用于Action
public ActionResult filteraction() { return View(); }
二、Controller的Filter
将Filter应用在Controller上有2种方式
1.直接将Filter应用在Controller上,如:
[TestFilter] public class EiceController : Controller { }
2.重写Controller内的
OnActionExecuting/OnActionExecuted/OnResultExecuting/OnResultExecuted的四个方法。下面我们说几个系统的Filter:
三、AcceptVerbs
规定页面的访问形式,如
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Example(){ return View(); }
四、ActionName
规定Action的名称。
应用场景:如果不想用方法名做为Action名,或Action名为关键字的话,如
[ActionName("class")] public ActionResult Example(){ return View(); }
五、NonAction
当前方法仅是普通方法不解析为Action
六、OutputCache
为Action添加缓存
[OutputCache(Duration = 60, VaryByParam = "*")] public ActionResult Example() { return View(); }
七、ValidateInput
该Action可以接受Html等危险代码(ASP. MVC在aspx中设置<%@ Page 的属性无法完成等同任务。)
[ValidateInput(false)] public ActionResult Example() { return View(); }
八、ValidateAntiForgeryTokenAttribute
用于验证服务器篡改。
[ValidateAntiForgeryToken] public ActionResult Example() { return View(); }
原文地址:http://www.25175.com/200609/25175/25175_html/2010-07/3537.html