Action filter and built-in filter implementation (Introduction)

Source: Internet
Author: User

Sometimes you want to process some logic before or after calling the action method. To support this, ASP. net mvc allows you to create an action filter. The action filter is a custom attributes used to mark the actions before or after the action method is added to the Action Method in the Controller class.

Some places that may use the action filter include:

  • Log, Exception Handling
  • Authentication and authorization-restrict user access
  • Output cache-Save the result of an action
  • Web Crawler Filtering
  • Localization
  • Dynamic Action-inject an action into the Controller

ASP. net mvc provides the following filter interfaces:

  • IActionFilter
  • IAuthorizationFilter
  • IExceptionFilter
  • IResultFilter

    To implement a filter, We need to inherit from the filterattribute class and simultaneously implement one or more of the above interfaces:

    Public class myfilter: filterattribute, iactionfilter, iresultfilter
    {
    }

    These interfaces provide the following methods:

    The method and the method corresponding to the filter interface can be seated by the name pair number.

    IActionFilterThe interface has two methods:

    Onactionexecuting is called before the action method is executed, and onactionexecuted is called after the action method is executed. Note that their parameters are actionexecutingcontext and actionexecutedcontext.

    The actionexecutedcontext class containsCanceledAllows you to cancel the current action.CanceledWhat if the attribute is missing in P5? Magic. How can I cancel an action during onactionexecuting ?).

    FilterexcutEdThe context class contains an exception attribute and an exceptionhandled attribute. If the exception attribute is null, no exception is found in action stack, indicating that the action method has not encountered an error. Otherwise, an exception occurs. If you set the exceptionhandled attribute to true, it indicates that an exception has been processed in the filter.

    The iresultfilter interface also provides two methods:

    They are executed before and after the return result (for example, return view ();) of the action. AndIActionFilterI will not say much about it.

    IAuthorizationFilterIs a filter used for identity authentication. Only one void onauthorization (authorizationcontext filtercontext) method is provided.

    IExceptionFilterIt is called when an exception occurs. It also provides only one void onexception (exceptioncontext filtercontext) method;

    These filters can be applied to classes or methods. Let's take a look at their execution sequence. First, write a basecontroller and add two filters:

    [Myfilter2 (target = "basecontroller")]
    [Myfilter1 (target = "basecontroller")]
    Public class basecontroller: Controller
    {
    }

    This should be because the Controller class implements these filter interfaces, So we re-write all the filter interfaces in the controller base class in homecontroller, add the custom myfilter in the homecontroller class and the filter method in it:

    Homecontroller
    [Myfilter2 (target = "homecontroller")]
    // [Myfilter1 (target = "homecontroller")] // note that myfilter1 is commented out here.
    [Handleerror]
    Public class homecontroller: basecontroller
    {
    [Myfilter2 (target = "homecontroller. filter")]
    [Myfilter1 (target = "homecontroller. filter")]
    Public actionresult filter ()
    {
    Return content ("<div> This is the content returned in the Action method! </Div> ");
    }

    Protected override void onactionexecuted (actionexecutedcontext filtercontext)
    {
    Filtercontext. httpcontext. response. Write ("<div> This is the content added by rewriting the onactionexecuted method in homecontroller! </Div> ");
    }

    Protected override void onactionexecuting (actionexecutingcontext filtercontext)
    {
    Filtercontext. httpcontext. response. Write ("<div> This is the content added by rewriting the onactionexecuting method in homecontroller! </Div> ");
    }

    Protected override void onauthorization (authorizationcontext filtercontext)
    {
    Filtercontext. httpcontext. response. Write ("<div> This is the content added by rewriting the onauthorization method in homecontroller! </Div> ");
    }

    Protected override void onexception (exceptioncontext filtercontext)
    {
    Filtercontext. httpcontext. response. Write ("<div> This is added by rewriting the onexception method in homecontroller! </Div> ");
    Filtercontext. exceptionhandled = true;
    }

    Protected override void onresultexecuted (resultexecutedcontext filtercontext)
    {
    Filtercontext. httpcontext. response. Write ("<div> This is the content added by rewriting the onresultexecuted method in homecontroller! </Div> ");
    }

    Protected override void onresultexecuting (resultexecutingcontext filtercontext)
    {
    Filtercontext. httpcontext. response. Write ("<div> This is the content added by rewriting the onresultexecuting method in homecontroller! </Div> ");
    }
    }

    Run the following command to check the result:

    From the running results, we can see that the filter that is rewritten in the Controller will be first executed, then applied to the filter on the class, and then applied to the filter on the class method.

    The execution sequence of the four interfaces is as follows:IAuthorizationFilter -> IActionFilter -> IResultFilter -> IExceptionFilter.

    For the same filter, for exampleThe implementation of iauthorizationfilter in myfilter1 and myfilter2 varies according to their loading sequence.

    The filter applied in basecontroller inherits the quilt class. If the subclass applies the same filter as the base class, the filter of the base class is not executed. For example, the preceding homecontroller applies myfilter2, so it calls myfilter2 of homecontroller instead of myfilter2 of basecontroller.

    This execution sequence can only be understood after a good study.

    Filterattribute also provides an order attribute to specify the execution sequence of the filter.

    Each action filter has an order attribute to determine the execution sequence of the Action filter in this range. The Order attribute must be 0 (default) or a greater integer. If the order attribute is omitted, the order value of the filter is-1, indicating that the order is not specified. Any action filter whose order is set to-1 in the same range will be executed in an uncertain order, but before that, the filter has a specific order (SEE ).

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

    Let's look at an example:

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

    The filter execution sequence is: filter3 => filter1 => filter2.

    For the time being, let's write so much. This part mainly introduces concepts. Enjoy! Post by Q. Lee. Lulu.

    Sample Code of the blog program in this article: actionfilter.rar

  • 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.