技术开发 频道

ASP.NET MVC Action Filter与内置的Filter实现

   这些Filter可以被应用在类或者方法上,下面我们来看一下他们的执行顺序。首先我们写一个BaseController并加上两个Filter: 

[MyFilter2(Target = "BaseController")]
[MyFilter1(Target
="BaseController")]
public class BaseController : Controller
{
}

  应为Controller类是实现这几个Filter接口的,所以我们在HomeController中重写Controller基类中的所有Filter接口的方法,并在HomeController类和里面的Filter方法加上我们自定义的MyFilter: 

HomeController
[MyFilter2(Target
= "HomeController")]
//[MyFilter1(Target = "HomeController")]//注意我在这里把MyFilter1注释了.
[HandleError]
public class HomeController : BaseController
{
    [MyFilter2(Target
= "HomeController.Filter")]
    [MyFilter1(Target
= "HomeController.Filter")]
    
public ActionResult Filter()
    {
        
return Content("<div>这是在Action方法里面返回的内容!</div>");
    }

    
protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.Write(
"<div>这是在HomeController里面重写OnActionExecuted方法添加的内容!</div>");
    }

    
protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Write(
"<div>这是在HomeController里面重写OnActionExecuting方法添加的内容!</div>");
    }

    
protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        filterContext.HttpContext.Response.Write(
"<div>这是在HomeController里面重写OnAuthorization方法添加的内容!</div>");
    }

    
protected override void OnException(ExceptionContext filterContext)
    {
        filterContext.HttpContext.Response.Write(
"<div>这是在HomeController里面重写OnException方法添加的内容!</div>");
        filterContext.ExceptionHandled
= true;
    }

    
protected override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.Write(
"<div>这是在HomeController里面重写OnResultExecuted方法添加的内容!</div>");
    }

    
protected override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Write(
"<div>这是在HomeController里面重写OnResultExecuting方法添加的内容!</div>");
    }
}

 

0
相关文章