Let me talk about the MVC filter, or the MVC filter.

Source: Internet
Author: User

Let me talk about the MVC filter, or the MVC filter.

Every request in APS. net mvc is allocated to the corresponding controller and corresponding behavior methods for processing, and additional logic processing is required before and after such processing. At this time, the filter is used.

In Asp. netMvc, you can use the Filter function when you have the following and similar requirements:

 

 

MVC supports four filter types: Authorization, Action, Result, and Exception ).

The following table

 

Filter Type

Interface

Description

Authorization

IAuthorizationFilter

This type (or filter) is used to restrict a behavior method to the Controller or controller.

Exception

IExceptionFilter

Specifies an action. This action is used to process an action method or an exception thrown in a controller.

Action

IActionFilter

Used for processing before or after a behavior

Result

IResultFilter

Used for processing before or after the returned results

 

However, there are only three filters implemented by default, namely Authorize (authorization), ActionFilter, and HandleError (error handling). The following table lists the information.

 

Filter

Class Name

Implementation Interface

Description

ActionFilter

AuthorizeAttribute

IAuthorizationFilter

This type (or filter) is used to restrict a behavior method to the Controller or controller.

HandleError

HandleErrorAttribute

IExceptionFilter

Specifies an action. This action is used to process an action method or an exception thrown in a controller.

Custom

ActionFilterAttribute

IActionFilter and IResultFilter

Used for processing before or after a behavior or before or after a returned result

 

1. Filter Applied to Action

To create an Action filter, you must implement the IActionFilter interface, which defines two methods.

 

Method Name Call time Available operations
OnActionExecuting Before the Action method is executed You can assign values to filterContext. Result to prevent Action execution.
You can use filterContext. ActionParameters to view or modify the Action parameters.
OnActionExecuted After the Action method is executed You can use filterContext. Exception to get the Exception thrown during Action execution and mark it as "handled": filterContext. ExceptionHandled = true.
You can view the execution Result of the Action through filterContext. Result, but it cannot be modified.

 

Action filters are inheritedActionFilterAttributeClass. ActionFilterAttribute is an abstract class that provides two virtual methods for us to override,OnActionExecutingAndOnActionExecuted.

The ASP. net mvc Framework will call the OnActionExecuting method in your Action filter before calling the Action method, and then call the OnActionExecuted method in the Action filter. Of course, you do not need to implement both methods when creating the Action filter.

 

The following example shows the log tracing before and after the Action method is called:

C # code Replication
public class LoggingFilterAttribute : ActionFilterAttribute {     public override void OnActionExecuting(FilterExecutingContext         filterContext)     {         filterContext.HttpContext.Trace.Write("Starting: " +          filterContext.ActionMethod.Name);     }      public override void OnActionExecuted(FilterExecutedContext         filterContext)     {         if (filterContext.Exception != null)         {             filterContext.HttpContext.Trace.Write("Exception thrown");         }     } }

 

Some parameter descriptions

 

Action Filter Context

The OnActionExecuting method has a type of FilterExecut.IngThe OnActionExecuted method has a corresponding type of FilterExcut.EdContext parameters. Both Context classes inherit from the FilterContext class, while the FilterContext class inherits from the ControllerContext class and contains an ActionMethod attribute. You can use the ActionMethod attribute to determine the Action method to which the Action filter is applied.

FilterExecutIngThe Context class contains a Cancel attribute that allows you to Cancel the current Action.

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. If the Exception attribute is not null, the filter knows how to handle the Exception. After the filter processes the Exception, it sends a signal that has been processed and sets the ExceptionHandled attribute to true. Even if the ExceptionHandled attribute is true, the OnActionExcetued method added to the stack to other Action methods will be called as usual. In this scenario, even if an exception is processed, the log record filter will be executed as usual.

 

Usage

You can apply the filter to any Action method you like. The following example shows an Action method included in the Controller marked with the Action filter Attribute.

C # code Replication
public class HomeController : Controller {     [LoggingFilter]     public void Index()     {         RenderView("Index");     }      [LoggingFilter]     public void About()     {         RenderView("About");     }      [LoggingFilter]     public void ClickMe()     {         HttpContext.Trace.Write("Button was clicked.");         InvokeAction("Index");     } }

 

Action filter scope

In addition to marking an Action method with the Action filter, you can also mark a completed controller class. In this case, the Action filter will be applied to all Action methods of the controller.

In addition, if your controller class inherits from another controller class, the base controller class may have its own Action filter Attributes. If you override the Action Method of the base controller class in the subclass, the Action Method of the subclass also has its own Attributes Action filter inherited from the base class.

 

Action filter execution sequence

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 specified. Any Action filter whose Order is set to-1 in the same range will be executed in an uncertain Order. Before that, the filter has a specific Order (Note: as mentioned below ).

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.

Example:

C # code Replication
  [Filter1(Order = 2)] [Filter2(Order = 3)] [Filter3(Order = 1)] public void Index() {     RenderView("Index"); }

The Filter execution sequence is: Filter3 => Filter1 => Filter2.

 

Ii. Filter of Controller

 

You can override the OnActionExecuting and OnActionExcuted methods defined by the ASP. net mvc Controller (Controller) class. When you override one or both methods, you actually define an Action filter that will be applied to all Action methods in the Controller class. Strictly speaking, this method does not constitute an Action filter, but in any case, they provide similar functions.

 

There are two ways to apply the Filter to the Controller:

1. Apply the Filter directly to the Controller, for example:

[TestFilter]
Public class EiceController: Controller
{
}

 

2. Rewrite


OnActionExecuting/OnActionExecuted/OnResultExecuting/OnResultExecuted.

 

In the following example, the Controller-level OnActionExecuting and OnActionExecuted methods are applied to all Action methods in the Controller:

C # code Replication
public class HomeController : Controller {     public void Index()     {         RenderView("Index");     }     public void About()     {         RenderView("About");     }     public void ClickMe()     {         HttpContext.Trace.Write("Button was clicked.");         InvokeAction("Index");     }     protected override void OnActionExecuting(FilterExecutingContext         filterContext)     {         filterContext.HttpContext.Trace.Write("Starting: " +              filterContext.ActionMethod.Name);     }     protected override void OnActionExecuted(FilterExecutedContext         filterContext)     {         if (filterContext.Exception != null)         {             filterContext.HttpContext.Trace.Write("Exception thrown");         }     } }

 

Iii. Filter filters commonly used in several systems

 

1. AcceptVerbs

Specifies the access form of the page, such

        [AcceptVerbs(HttpVerbs.Post)]         public ActionResult Example(){             return View();         }


Pages can only be accessed in the form of Post, that is, form submission.

 

2. ActionName

Specifies the name of the Action.

Application Scenario: if you do not want to use the method name as the Action name or the Action name as the keyword, for example

       [ActionName("class")]         public ActionResult Example(){             return View();         }

 

3. NonAction

The current method is only a common method and is not parsed as an Action.

 

4. OutputCache

Add cache for Action

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

 

5. ValidateInput

This Action can accept Html and other dangerous code (ASP. net mvc cannot complete equivalent tasks by setting the <% @ Page attribute in aspx .)

        [ValidateInput(false)]        public ActionResult Example()        {            return View();        }

 

6. ValidateAntiForgeryTokenAttribute

Used to verify server tampering.

        [ValidateAntiForgeryToken]        public ActionResult Example()        {            return View();        }

Related Article

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.