Use the ASP.NET MVC- ActionFilter

First understand what is: ActionFilter

1: ActionFilter is interspersed in the process of implementation of Action, provides extended functionality before and after the implementation of Action. ActionFilter use very wide, with page compression, caching, error handling, login authentication.

2: ActionFilter implementation requires ActionFilterAttribute inherit from the abstract class, and covers the need to use the method.

3: There are four methods can ActionFilterAttribute weight classes, namely OnActionExecuting, OnActionExecuted, OnResultExecuting, OnResultExecuted.

4: execution order of these four methods is OnActionExecuting-> OnActionExecuted-> OnResultExecuting-> OnResultExecuted

Implementation steps: usually build a folder dedicated to put a filter class, where I built a Filter file folder, placed inside a class TestFilter

 

Class code as follows:

namespace FirstMvcDemo.Filter 
{ 
    public  class TestFilter: the ActionFilterAttribute 
    { 
        public  the override  void the OnActionExecuting (ActionExecutingContext filterContext) 
        { 
            // if you want to use the content or ViewBag ViewData like controller, the parameters used in the method filterContext.Controller 
            filterContext.Controller.ViewBag. = the TestData " content. 1 " ; 
            filterContext.Controller.ViewData [ " the TestData " ] = " content 2 " ; 
            HttpContext.Current.Response.Write ( " time about ready to perform Action executed but not yet executed when "); 
        } 

        Public  the override  void the OnActionExecuted (ActionExecutedContext filterContext) 
        { 
            HttpContext.Current.Response.Write ( " but has not executed when execution returns results Action " ); 
        } 

        public  the override  void the OnResultExecuting (ResultExecutingContext filterContext) 
        { 
            HttpContext.Current.Response. the Write ( " the OnResultExecuting OnActionExecuted and also the same, but the former is performed only after the implementation of the latter " ); 
        } 

        public  the override  void OnResultExecuted (ResultExecutedContext filterContext) 
        {
            HttpContext.Current.Response.Write ( " the Action to be executed after return ActionResult Executes " ); 
        } 
    } 
}

Then in the Controller, the plus [TestFilter] flag is in the implementation of this Action will first enter FilterDemo class, the implementation of which method

[TestFilter]
public ActionResult Home() 
{
    return View();
}

Of course, filter class put in the position if not possible references do not forget on the line!

Guess you like

Origin www.cnblogs.com/dcy521/p/11416346.html