Each request in Aps.net MVC is assigned to the appropriate controller and corresponding behavior method to process, and in the back and forth of these processing if you want to add some additional logic processing. The filter is used at this time.
In ASP.NETMVC you can use the filter function when you have the following and similar requirements
- Determine login or user rights
- Decision output Cache
- Anti-theft chain
- Anti-Spider
- Localization and internationalization settings
- Implementing Dynamic Action
There are four types of filters supported by MVC: Authorization (Authorization), Action (behavior), result (result), and exception (exception).
As the following table
filter type |
interface |
description |
authorization |
iauthorizationfilter |
This type (or filter) is used to restrict a behavior method that enters a controller or controller |
exception |
iexceptionfilter |
|
action |
iactionfilter |
processing before or after entering the behavior |
result |
iresultfilter |
|
However, there are only three filters implemented by default, authorize (authorization), Actionfilter,handleerror (error handling), and various information as shown in the following table
Filter filters |
Class name |
Implementing interfaces |
Describe |
Actionfilter |
Authorizeattribute |
Iauthorizationfilter |
This type (or filter) is used to restrict access to a behavior method of the controller or controller |
HandleError |
Handleerrorattribute |
Iexceptionfilter |
Used to specify a behavior that the specified behavior handles a behavior method or an exception thrown in a controller |
Custom |
ActionFilterAttribute |
Iactionfilter and Iresultfilter |
Handling before or after processing or returning results before or after entering the behavior |
A filter applied to the action
Creating an Action filter must implement the Iactionfilter interface, which defines two methods
Method name |
Call timing |
Operational actions that can be performed |
OnActionExecuting |
Before the action method executes |
You can assign a value to Filtercontext.result to prevent the action from executing You can view or modify the Action's parameters through Filtercontext.actionparameters |
onactionexecuted |
After the action method executes |
The exception that is thrown when the action executes can be obtained through filtercontext.exception and can be marked as handled: Filtercontext.exceptionhandled = True. You can view the execution results of an Action through Filtercontext.result, but you cannot modify it. |
The action filter is a attribute class that is implemented by inheriting the ActionFilterAttribute class. ActionFilterAttribute is an abstract class that provides two virtual methods for us to rewrite,onactionexecuting and onactionexecuted.
The ASP. NET MVC Framework calls the OnActionExecuting method in your action filter before calling the action method, and then calls the OnActionExecuted method in the action filter. Of course, you don't need two ways to do this when creating an action filter.
The following example is a log trace before and after calling the action method:
C # codeCopy
Public ClassLoggingfilterattribute: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 " ); } } /span>
Partial parameter description
Action Filter Context
The OnActionExecuting method has a parameter of type filterexecutingContext , and the OnActionExecuted method has a corresponding type of FilterexcutEdContext parameters. The two context classes inherit from the Filtercontext class, and the Filtercontext class inherits from the ControllerContext class and contains a Actionmethod property. You can use the Actionmethod property to resolve which action method the action filter is applied to.
The filterexecutingContext class contains a Cancel property that allows you to cancel the current action.
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. If the exception property is not NULL, the filter knows what to do, the filter finishes processing the exception, emits a signal that has been processed, and then sets the Exceptionhandled property to True. Even if the Exceptionhandled property is True, the onactionexcetued method that is added to the other action method on the stack will be called as usual, such as if an exception is handled and the log record filter executes as usual.
How to use
You can apply a filter to any action method you like. The following example shows an action method contained in a controller that is marked with the action filter attribute.
C # codeCopy
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 " ); } /span>
Action Filter's scope
In addition to tagging an action method with the action filter, you can also mark a completed controller class. If so, the action filter will be applied to all the action methods of the Controller.
Also, 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 a subclass, the action method of the subclass also has its own action filter attributes inherited from the base class.
The execution order of the action 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 the order. Any action filter in the same range with the order set to 1 will be executed in an indeterminate order before the filter has a specific order (note: below).
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.
Example:
C # codeCopy
=2=3=1publicvoid{Renderview ("Index");}
The filter is executed in the following order: Filter3 = Filter1 = Filter2.
Second, the Controller's filter
The onactionexecuting and onactionexcuted methods defined by the ASP. NET MVC controller class can be overridden. When you rewrite one or both of these methods, you actually define an action filter that will be applied to all the action methods in the Controller class. Strictly speaking, this method does not constitute an action filter, but in any case, the functionality they provide is similar.
There are 2 ways to apply the filter to the controller
1. Apply the filter directly to the controller, such as:
[Testfilter]
public class Eicecontroller:controller
{
}
2. Rewrite the controller within the
Four methods of onactionexecuting/onactionexecuted/onresultexecuting/onresultexecuted.
In the following example, the OnActionExecuting and OnActionExecuted methods at the controller level are applied to all the action methods in the controller:
C # codeCopy
Public ClassHomecontroller:controller{Public voidIndex (){Renderview ("Index"); } Public voidAbout (){Renderview ("About"); } Public voidClickMe (){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 " ); } } /span>
Three, several systems commonly used filter filters
1, 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.
2, 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 (); }
3, Nonaction
The current method is only normal method does not resolve to action
4, OutputCache
Add a cache for an action
[OutputCache (Duration = $, VaryByParam = "*")] Public ActionResult Example () { return View (); }
5, 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 (); }
6, Validateantiforgerytokenattribute
Used to verify server tampering.
[Validateantiforgerytoken] Public ActionResult Example () { return View (); }
I say MVC filter