Go Introduction to ASP. 9, Action Filter and built-in filter implementation (introduction)

Source: Internet
Author: User

There are times when you want to handle some logic before invoking the action method or after the action method, in order to support this, ASP. NET MVC allows you to create an action filter. The action filter is a custom attributes that is used to mark the behavior of the action method before or after the action method is added to the action method in the Controller class.

Some of the areas where action filters may be used are:

    • Log, exception handling
    • Authentication and authorization-restricting access to users
    • Output cache-Saves the result of an action
    • Filtering of web Crawlers
    • Localization
    • Dynamic action-injects an action into the controller

ASP. NET MVC provides us with the following filter interfaces:

    • IActionFilter
    • IAuthorizationFilter
    • IExceptionFilter
    • IResultFilter

      To implement a filter, we need to inherit from the FilterAttribute class and implement one or several of the interfaces above:

      public class Myfilter:filterattribute, Iactionfilter, Iresultfilter
      {
      }

      These interfaces provide the following methods:

      Method and the filter interface corresponding to the method by name.

      IActionFilterThe interface has two methods:

      Where OnActionExecuting is called before the action method executes, onactionexecuted is called after the action method executes. Note that their parameters are actionexecutingcontext and actionexecutedcontext respectively.

      The ActionexecutEdContext class contains a Canceled attribute that allows you to cancel the current action (how the original in P3 is in actionexecuting The Canceled attribute of the context is not in the P5? Magic. So how do you cancel an action when you're onactionexecuting? )。

      The filterexcutEdContext class contains a exception property and a Exceptionhandled property. If the exception property is null, there is no exception in the action stack, indicating that the action method ran without an error. Conversely, an exception occurs. Setting the Exceptionhandled property to True indicates that an exception has been handled in this filter.

      IResultFilter接口也提供了两个方法:

      They are executed before and after the action returns the result (for example, return View ();). and IActionFilter almost not much to say.

      IAuthorizationFilteris a filter for authentication. Only one void Onauthorization (AuthorizationContext Filtercontext) method is provided.

      IExceptionFilterwill be called in the event of an exception, and is a method that only provides a void Onexception (Exceptioncontext filtercontext);

      These filter can be applied to classes or methods, let's take a look at their execution order. First we write a basecontroller and add two filter:

      [MyFilter2 (Target = "Basecontroller")]
      [MyFilter1 (target= "Basecontroller")]
      public class Basecontroller:controller
      {
      }

      The controller class is supposed to implement these filter interfaces, so we rewrite the method of all the filter interfaces in the Controller base class in HomeController, And in the HomeController class and inside the filter method plus our custom myfilter:


      [MyFilter2 (Target = "HomeController")]
      [MyFilter1 (Target = "HomeController")]//note I've commented on MyFilter1 here.
      [HandleError]
      public class Homecontroller:basecontroller
      {
      [MyFilter2 (Target = "Homecontroller.filter")]
      [MyFilter1 (Target = "Homecontroller.filter")]
      Public ActionResult Filter ()
      {
      Return content ("<div> This is what is returned in the action Method!) </div> ");
      }

      protected override void OnActionExecuted (ActionExecutedContext filtercontext)
      {
      FilterContext.HttpContext.Response.Write ("<div> This is the content added in HomeController to rewrite the onactionexecuted Method! </div> ");
      }

      protected override void OnActionExecuting (ActionExecutingContext filtercontext)
      {
      FilterContext.HttpContext.Response.Write ("<div> This is the content added in HomeController to rewrite the OnActionExecuting Method! </div> ");
      }

      protected override void Onauthorization (AuthorizationContext filtercontext)
      {
      FilterContext.HttpContext.Response.Write ("<div> This is the content added in HomeController to rewrite the Onauthorization Method! </div> ");
      }

      protected override void Onexception (Exceptioncontext filtercontext)
      {
      FilterContext.HttpContext.Response.Write ("<div> This is the content added in HomeController to rewrite the Onexception Method! </div> ");
      Filtercontext.exceptionhandled = true;
      }

      protected override void Onresultexecuted (ResultExecutedContext filtercontext)
      {
      FilterContext.HttpContext.Response.Write ("<div> This is the content added in HomeController to rewrite the onresultexecuted Method! </div> ");
      }

      protected override void Onresultexecuting (ResultExecutingContext filtercontext)
      {
      FilterContext.HttpContext.Response.Write ("<div> This is the content added in HomeController to rewrite the Onresultexecuting Method! </div> ");
      }
      }

      Then let's run it and see how the results are:

      From the running result we can see that the filter overridden in the controller is executed first, then to the filter applied on the class, and then to the filter applied on the class method.

      The method execution order of the 4 interfaces is as follows: IAuthorizationFilter ->  IActionFilter -> IResultFilter -> IExceptionFilter .

      For the same filter, for example,IAuthorizationFilter在MyFilter1和MyFilter2里里面的实现,又根据他们的加载顺序不同而不同。

      在BaseController中应用的Filter会被子类继承,如果子类又应用了和基类同样的Filter,则会不执行基类的Filter。例如上面的HomeController应用了MyFilter2,所以调用HomeController的MyFilter2,而不是BaseController的MyFilter2。

      这个执行顺序还得大家好好研究才能了解的。

      同时FilterAttribute还提供了一个Order的属性,用于指定Filter的执行顺序。

      Each action filter has an order property that determines the order in which the action filter executes within that range. The Order property must be 0 (the default) or a larger integer value. Omitting the Order property gives the filter an order value of-1, indicating that the order is not specified. Any action filter in the same range with the order set to 1 will be executed in an indeterminate order, but before this filter has a specific order (refer to).

      When setting the value of the Order property, you must specify a unique value. If two or more action filters have the same order attribute value, an exception will be thrown.

      Consider an example:

      [Filter1 (Order = 2)]
      [Filter2 (Order = 3)]
      [Filter3 (Order = 1)]
      public void Index ()
      {
      Renderview ("Index");
      }

      The filter is executed in the following order: Filter3 = Filter1 = Filter2.

      Write so much for the time being, this part mainly introduces the concept. enjoy! Post by Q.lee.lulu.

      This article's blog Program Sample code: Actionfilter.rar

Go Introduction to ASP. 9, Action Filter and built-in filter implementation (introduction)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.