"Go" ASP. NET MVC3 simple Getting Started detailed filters filter

Source: Internet
Author: User

Original address: http://www.cnblogs.com/boruipower/archive/2012/11/18/2775924.html

Objective

In the development of large projects there will always be related AOP-oriented components of the aspect programming, and MVC (specifically: ASP. NET MVC, the following) project does not want to let the MVC developers to care about and write similar authentication, log, exception, behavior interception and so on this part of the duplicated code, We can do this through AOP, and in the MVC project we can directly use the filter features provided by it to help us solve it without having to implement complex AOP ourselves.

in ASP. NET MVC you can use the filter function when you have the following and similar requirements

    1. Determine login or user rights
    2. Decision output Cache
    3. Anti-theft chain
    4. Anti-Spider
    5. Localization and internationalization settings
    6. Implementing Dynamic Action
Section I: Knowledge reserve

ASP. NET MVC provides the following types of default filter:

Filter Type

Implementing interfaces

Execution time

Default implementation

Authorization Filter

Iauthorizationfilter

Execute before all filter and action are executed

Authorizeattribute

Action Filter

Iactionfilter

Execute before and after action execution, respectively.

ActionFilterAttribute

Result Filter

Iresultfilter

After the action result is executed and before

Resultfilterattribute

Exception Filter

Iexceptionfilter

Only in filter,

Or action method, or action result throws an exception when executing

Handleerrorattribute

It is important to note that the ActionFilterAttribute provided by ASP. NET MVC implements Iactionfilter and Iresultfilter by default. While ActionFilterAttribute is an abstract type, it cannot be used directly because it cannot be instantiated, so we want to use it to inherit it before it can be used.

Filter inherits from the ActionFilterAttribute abstract class and can overwrite void onactionexecuting (ActionExecutingContext) and void onactionexecuted ( ActionExecutedContext) as well as void onresultexecuting (ResultExecutingContext) and void onresultexecuted ( ResultExecutedContext).

They are executed in the following order:

OnActionExecuting is the action before action is executed

OnActionExecuted is the action performed after action

Onresultexecuting is performed before parsing ActionResult

Onresultexecuted is performed after parsing ActionResult

Next we can just rewrite the above method to do something in the corresponding steps.

Section II: Filter Combat

Light say not practice false bashi, below I give you an example, to see their execution order

First, add an ordinary class, this class to inherit ActionFilterAttribute, directly on the code

   public class Testfilterattribute:actionfilterattribute {public string Message {get; set;} public override void OnActionExecuting (ActionExecutingContext filtercontext) {base.            OnActionExecuting (Filtercontext);        FilterContext.HttpContext.Response.Write ("+message+" before action executes "<br/>"); } public override void OnActionExecuted (ActionExecutedContext filtercontext) {base.            OnActionExecuted (Filtercontext);        FilterContext.HttpContext.Response.Write ("+message+" after action executes "<br/>"); } public override void Onresultexecuting (ResultExecutingContext filtercontext) {base.            Onresultexecuting (Filtercontext);        FilterContext.HttpContext.Response.Write ("+message+" <br/> "before returning result); } public override void Onresultexecuted (ResultExecutedContext filtercontext) {base.            Onresultexecuted (Filtercontext); Filtercontext.httpcontext.        Response.Write ("Return result" +message+ "<br/>"); }    }

After writing this code, we go back to the action and hit the above tag as follows:

[Testfilter (message= "Action")]        Public ActionResult Index ()        {            HttpContext.Response.Write ("Action is executing ... <br/> ");            Return Content ("Returning result <br/> ");        }

Then you can see the following execution order by accessing the action above from the browser

The total order of execution is:

before action executes: The OnActionExecuting method executes the →action execution →onactionexecuted method execution →onresultexecuting Method execution → Actionrsult method in the returned Executeresult Line →onresultexecuted execution . The effect of the final display is as shown.

It feels good! Oh! If you want to use this filtering mechanism, just add a tag to the action to achieve the effect.

If we hit this tag on the controller, the Testfilterattributefilter will act on all actions under the controller. For example, the following code shows:

[Testfilter (message= "Controller")]    public class Testfiltercontroller:controller    {        ////        GET:/testfilter/        [Testfilter (message= "Action ")] public        actionresult Index ()        {            HttpContext.Response.Write (" Action is executing ... <br/> ");            Return Content ("Returning result <br/> ");        }    }

If we simply follow the code above, there is a problem. What happens when we execute the displayed page? Will the filter on the controller execute? Does that label work two times? The following is the final execution result as shown in:

The result: By default, when the Testfilterattribute tag is hit on the action, the tag is also on the controller, but it only works on the tag on the action.

Add: If the action does not have a testfilterattribute tag, the tag on the controller will be executed.

When Index is executed, the filter method executes only once, and in some cases we want filterattribute on the controller to perform a testfilterattribute, so how can we get the controller to [ Testfilter (Message = "Controller")] also play a role?

The answer is: We simply mark the definition of the Testfilterattribute class [AttributeUsage (AttributeTargets.All, AllowMultiple = True)]. The topmost red font section of the following class, which makes it an action that can be executed more than once. the code is as follows:

  [AttributeUsage (Attributetargets.all,allowmultiple = True)] public class Testfilterattribute:actionfilterattribute        {public string Message {get; set;} public override void OnActionExecuting (ActionExecutingContext filtercontext) {base.            OnActionExecuting (Filtercontext);        FilterContext.HttpContext.Response.Write ("+message+" before action executes "<br/>"); } public override void OnActionExecuted (ActionExecutedContext filtercontext) {base.            OnActionExecuted (Filtercontext);        FilterContext.HttpContext.Response.Write ("+message+" after action executes "<br/>"); } public override void Onresultexecuting (ResultExecutingContext filtercontext) {base.            Onresultexecuting (Filtercontext);        FilterContext.HttpContext.Response.Write ("+message+" <br/> "before returning result); } public override void Onresultexecuted (ResultExecutedContext filtercontext) {base. OnResultexecuted (Filtercontext);        FilterContext.HttpContext.Response.Write ("Return result" +message+ "<br/>"); }    }

Browsing effects such as:

The result we see is that the Actionfilter on the controller is executed before the tag on the action. The same result executes the Onresultexecuteing method in the filter tag on the controller before executing the Executeresult method.

The final order of execution is:  The onactionexecuting→action on the onactionexecuting→action on the controller executes onactionexecuted on the Onactionexecuted→controller on the →action.

When this action is done, we see that it is the order in which the stack is stacked. After the action returns ActionResult, the Executeresult method is executed, but the filter is executed before execution. The specific order is:

Pick up the top → The controller's Onresultexecuting method →action on Onresultexecuting→action returns ActionResult after the Executeresult method →action is executed onresultexecuted Perform the onresultexecuted execution → End on the →controller.

And then another question comes, and we think that some common methods require each action to execute the following, and it is painful to tag all controllers. Fortunately, ASP. Net MVC3 brings a nice thing to the global filter. And how to register the global filter? The answer is in the Global.asax. Let's look at the following code, how I registered the Testfilterattribute we defined above into the global filter. On the code:

public static void Registerglobalfilters (Globalfiltercollection filters)        {            filters. ADD (New Handleerrorattribute ());            Registers the global filter            filters. ADD (New Testfilterattribute () {message= "global"});        

Effects such as:

The result we see is that the global action executes first, then the filter execution under the controller, and finally the tag execution on the action. This is, of course, marked on the definition of the Testfilterattribute class [AttributeUsage (AttributeTargets.All, AllowMultiple = True)]. Otherwise, if the action is labeled the same as the controller, it will only execute the filter on the action.

Below we say a few system filter Third, Acceptverbs

Specifies the form of access to the page, such as

        [Acceptverbs (Httpverbs.post)]
Public ActionResult Example () {
return View ();
}


The page can only be accessed as post, which is the form submission.

Iv. ActionName

Specifies the name of the action.

Scenario: If you do not want to use the method name as the action name, or if the action name is a keyword, such as

       [ActionName ("Class")]
Public ActionResult Example () {
return View ();
}

Wu, Nonaction

The current method is only normal method does not resolve to action

Liu, OutputCache

Add a cache for an action

        [OutputCache (Duration = $, VaryByParam = "*")]
Public ActionResult Example ()
{
return View ();
}

Seven, ValidateInput

The action can accept dangerous code such as HTML (the properties of ASP. NET MVC set <%@ Page in ASPX cannot complete the equivalent task.) )

        [ValidateInput (False)]
Public ActionResult Example ()
{
return View ();
}

Eight, Validateantiforgerytokenattribute

Used to verify server tampering.

        [Validateantiforgerytoken]
Public ActionResult Example ()
{
return View ();
}
Summarize

After the introduction of this article we generally understand the use of the filter, but also understand the usage of the global filter, especially when the same filter repeated action on the same action, if there is no set of tags can be executed more than the filter execution on the action, Both the controller and the global filter are masked, but the settings can be executed multiple times, and the first global filter is followed by the controller again as the filter on the action. We also understand the use of the filter in the system.

Boruipower

Source: Http://www.cnblogs.com/boruipower

qq:1318854011

Shop: http://gz168168.taobao.com

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.