ASP.NET MVC 过滤器
过滤器又叫筛选器,一般有三种过滤器,一个是aciton过滤器,也就是执行action之前和之后,还一种是view过滤器,就是加载view之前和之后,最后一种就是异常过滤器,是异常后触发的。
很简单,只要类实现了ActionFilterAttribute这个接口,并重写里面的方法便可。上代码,一看便知
原文地址:http://www.cnblogs.com/sixiangqimeng/p/3567716.html
public class MyActionFileterAttribute :ActionFilterAttribute { public string Name { get; set; } //当Action执行之前先执行此代码 public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); filterContext.HttpContext.Response.Write("<p>当前是:OnActionExecuting by "+Name+"</p>"); } public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); filterContext.HttpContext.Response.Write("<p>当前是:OnActionExecuted by " + Name + "</p>"); } public override void OnResultExecuting(ResultExecutingContext filterContext) { base.OnResultExecuting(filterContext); filterContext.HttpContext.Response.Write("<p>当前是:OnResultExecuting by " + Name + "</p>"); } public override void OnResultExecuted(ResultExecutedContext filterContext) { base.OnResultExecuted(filterContext); filterContext.HttpContext.Response.Write("<p>当前是:OnResultExecuted by " + Name + "</p>"); } }
实现时只需在控制器方法上加上[MyActionFileter(Name = "About ")]。
也可以设置全局的,整个项目都设置过滤器,秩序在过滤器设置里面设置
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyExceptionFilterAttribute());
filters.Add(new MyActionFileterAttribute(){Name = "gloable"});
}
设置一个全局的即可