ASP. NET has no magic -- ASP. net mvc Filter (Filter), mvcfilter

Source: Internet
Author: User

ASP. NET has no magic -- ASP. net mvc Filter (Filter), mvcfilter

The previous article introduced how to use the Authorize feature to implement ASP. net mvc authorization for Controller or Action. In fact, this feature is part of the MVC function, known as Filter, which is an implementation of Aspect-oriented programming (AOP, this chapter introduces ASP from the following aspects. net mvc filters.

● Filters and their types in ASP. NET MVC
● Filters commonly used in ASP. NET MVC
● ASP. net mvc Filter Application Method
● ASP. net mvc Action method call and Filter execution
● ASP. net mvc filter creation and Acquisition
● ASP. net mvc Action and Result filter pipeline execution

Filters and their types in ASP. NET MVC

In the previous Entity Framework article, we introduced the interceptors function of EF, ASP. net mvc filters are similar to interceptors in programming for aspect (AOP). They are a programming method that expands applications without modifying the source code. Generally, AOP is used to process logging, Performance Statistics, security control, transaction processing, Exception Processing, and other functions that do not modify the original business data.
ASP. net mvc divides filters into the following categories, each of which is defined through a corresponding interface:
● IAuthenticationFilter: this filter is added to MVC5 and has the highest priority among all filters, you can use the authentication filter to add authentication logic for Action, Controller, or all controllers. The core of the authentication filter is to create a Principal object based on the request information (Note: using Identity authentication is actually creating a Principal object). The following is the definition of IAuthenticationFilter:

  

The authentication context has an IPrincipal attribute:

  

● IAuthorizationFilter: The authorization filter is used to process access restrictions of controllers and actions.
● Action Method filter: The Action filter can be used to add logic before and after the Action method is executed.
● IResultFilter: You can add logic before and after execution of the result filter. (Note: The Action returned by ASP. net mvc is of the ActionResult type. This abstract type defines an execution method ExecuteResult. The execution of the result actually processes the returned result)

  

For example, if FileResult is executed, an appropriate parameter is added to the Http response header and the binary data of the file is written to the response body, which is equivalent to the file download function.

  

More execution results will be introduced in subsequent articles.

● Exception filter: when the Action method throws an exception during execution, it is used to add a filter for exception handling logic.

Filters commonly used in ASP. NET MVC

The filter category is introduced above. Now we will introduce the common filters under each category:
● IAuthenticationFilter: Because the Identity authentication process can be completed by using mature components such as Identity, no suitable filter is found for the authentication filter. You can customize the system if necessary.
● IAuthorizationFilter ):
○ Authorize: user authorization based on user name and role.
○ RequireHttps: Https-Based Access authorization.
○ ValidateInput: ASP. net mvc will verify whether the request information contains illegal information such as HTML before execution to avoid XSS attacks, but sometimes it is necessary to submit HTML data, when you submit the data, you can use this filter to set EnableValidation to false. MVC will skip data verification.
○ ValidateAntiForgeryToken: this filter can verify the anti-counterfeit token generated by the AntiForgeryToken method of HtmlHelper to prevent cross-site forgery of CSRF attacks.
● Action filter: It is generally customized as needed.
● Exception filter ):
○ HandleError: used to handle exceptions thrown by the Action method (a global HandleError filter is added to the default MVC template ).

In addition, the Controller in ASP. net mvc is actually a filter, because the Controller base class implements all the filter interfaces:

  

Therefore, if a Controller has special processing requirements and does not need to define a filter, you can simply reload the corresponding filter in the Controller:

  

Application Method of ASP. net mvc Filter

Filters in ASP. net mvc can be used in the following ways:
1. the filter is marked on the Controller and Action by using features. However, you must note that the filter used by features must be encapsulated into a filter interface in addition to implementing the corresponding filter interface. net features and IMvcFilter interface implementation, the most convenient is to directly inherit the FilterAttribute type implementation, such:

  

2. Add a filter through the Global filter table. The added filter will take effect for the Action methods of All controllers.

  

3. The Controller type is implemented by reloading the corresponding filter method. The above shows that the Controller itself is a type that implements all filters.

ASP. net mvc Action method call and Filter execution

The filter is called and executed during the Action method execution. Therefore, you must first understand the Action execution process. In the previous article, we introduced how to create and execute Controller ASP. NET has no magic -- ASP. net mvc Controller instantiation and execution, which is based on this article to introduce the Action execution process. Controller execution is completed through the Controller-type ExecuteCore method:

  

In the code, we can also see that the Controller actually calls the Action method execution based on the Action name through ActionInvoker. In ASP. net mvc uses an asynchronous Action caller named AsyncControllerActionInvoker by default:

  

In addition to the asynchronous function, it also inherits the synchronous ControllerActionInvoker type. asynchronous mainly aims to improve the throughput of request processing. Here we will use the code of the synchronous version to introduce the execution of Action and Filter.

ControllerActionInvoker:

   

The following points can be seen from the Code definition:
1. Its core method is InvokeAction, which processes the call processing logic of all filters and actions.
2. The GetFilters method is used to obtain all related filters.
3. InvokeActionMethodWithFilters, InvokActionResultWitherFilters, InvokeAuthenticationFilters, InvokeAuthenticationFiltersChallenge, InvokeAuthorizationFilters, InvokeExceptionFilters, and other related methods are used to call the corresponding filter execution Method.
Here, we use source code analysis to introduce the execution process of the filter in ActionInvoker:

1 // <summary> Invokes the specified action by using the specified controller context. </summary> 2 // <returns> The result of executing the action. </returns> 3 // <param name = "controllerContext"> The controller context. </param> 4 // <param name = "actionName"> The name of the action to invoke. </param> 5 // <exception cref = "T: System. argumentNullException "> The <paramref name =" controllerContext "/> par Ameter is null. </exception> 6 // <exception cref = "T: System. argumentException "> The <paramref name =" actionName "/> parameter is null or empty. </exception> 7 // <exception cref = "T: System. threading. threadAbortException "> The thread was aborted during invocation of the action. </exception> 8 // <exception cref = "T: System. exception "> An unspecified error occurred during invocation of the action. </Ti On> 9 public virtual bool InvokeAction (ControllerContext controllerContext, string actionName) 10 {11 if (controllerContext = null) 12 {13 throw new ArgumentNullException ("controllerContext "); 14} 15 if (string. isNullOrEmpty (actionName )&&! ControllerContext. routeData. hasDirectRouteMatch () 16 {17 throw new ArgumentException (MvcResources. common_NullOrEmpty, "actionName"); 18} 19 ControllerDescriptor controllerDescriptor = this. getControllerDescriptor (controllerContext); 20 ActionDescriptor actionDescriptor = this. findAction (controllerContext, controllerDescriptor, actionName); // obtain the description of the Action according to the Controller Information and Action name 21 if (actionDescriptor! = Null) 22 {23 FilterInfo filters = this. getFilters (controllerContext, actionDescriptor); // obtain all filters 24 try25 {26 AuthenticationContext authenticationContext = this. invokeAuthenticationFilters (controllerContext, filters. authenticationFilters, actionDescriptor); // call the authentication filter 27 if (authenticationContext. result! = Null) 28 {29 login AuthenticationChallengeContext = this. attributes (controllerContext, filters. AuthenticationFilters, actionDescriptor, authenticationContext. Result); 30 this. InvokeActionResult (controllerContext, condition. Result ?? AuthenticationContext. Result); 31} 32 else33 {34 AuthorizationContext authorizationContext = this. InvokeAuthorizationFilters (controllerContext, filters. AuthorizationFilters, actionDescriptor); // call authorization filter 35 if (authorizationContext. Result! = Null) 36 {37 AuthenticationChallengeContext attributes = this. attributes (controllerContext, filters. AuthenticationFilters, actionDescriptor, authorizationContext. Result); 38 this. InvokeActionResult (controllerContext, role ?? AuthorizationContext. result); 39} 40 else41 {42 if (controllerContext. controller. validateRequest) // determines whether the request needs to be verified. When the ValidateInput feature is used and the EnableValidation is set to False, the verification is skipped. 43 {44 ControllerActionInvoker. validateRequest (controllerContext); 45} 46 IDictionary <string, object> parameterValues = this. getParameterValues (controllerContext, actionDescriptor); 47 ActionExecutedContext actionExecutedContext = this. invokeActi OnMethodWithFilters (controllerContext, filters. actionFilters, actionDescriptor, parameterValues); // executes the Action filter and Action Method 48 AuthenticationChallengeContext authenticationChallengeContext3 = this. invokeAuthenticationFiltersChallenge (controllerContext, filters. authenticationFilters, actionDescriptor, actionExecutedContext. result); 49 this. invokeActionResultWithFilters (controllerContext, filters. resultFi Lters, authenticationChallengeContext3.Result ?? ActionExecutedContext. result); // execute the Result filter and Result50} 51} 52} 53 catch (ThreadAbortException) 54 {55 throw; 56} 57 catch (Exception exception) 58 {59 ExceptionContext exceptionContext = this. invokeExceptionFilters (controllerContext, filters. exceptionFilters, exception); // execute the exception filter 60 if (! Predictioncontext. exceptionHandled) // If the exception filter does not handle the exception, it will continue to throw the exception 61 {62 throw; 63} 64 this. invokeActionResult (controllerContext, exceptionContext. result); 65} 66 return true; 67} 68 return false; 69}View Code

Through the analysis of the above code, we can draw the following conclusions:
1. Find the actual Action method through the context and Action information of the Controller and obtain all the filters.
2. Perform the authentication filter first.
3. Execute the authorization filter after passing the authentication filter.
4. After the authorization filter is passed, execute the Action filter and Action method.
5. Execute the Result filter and Result.

ASP. net mvc filter creation and Acquisition

According to the above introduction, we know that you can apply filters by using the Global filter, feature tag, and overload Controller filter methods, so how does one create and retrieve them through the GetFilters method of ActionInvoker during execution?
● FilterProvider: ASP. net mvc has the concept and actual object of a filter provider. Three implementations correspond to the above three application methods respectively:
○ GlobalFilterCollection: used to save the global filter instance. You can directly add and obtain the filter instance through it. The Scope of the filter created through it is Gobal, the Order parameter can be used to determine the execution sequence of the global filter:

  

○ FilterAttributeFilterProvider: the filter feature provider that creates a filter by searching for the Controller and the features on the Action. Based on the feature tag location, the Scope is divided into Controller and Action, when applying a feature, you can set the Order attribute of the feature to determine the execution sequence of the filter:

    

○ ControllerInstanceFilterProvider: Controller instance filter provider, which is used to obtain the filter of the current Controller instance and the Scope of the filter is First:

    

● FilterProviderCollection: it contains all the filter providers mentioned above, and ActionInvoker obtains all related filters through it:

  

When the FitlerProviderCollection collection gets the filter, it obtains all the related filters through the above three providers and sorts the filters according to Scope and Order to determine the filter execution sequence.

ASP. net mvc Action and Result filter pipeline execution

There are two methods in the definitions of Action and Result filters: OnXXXExecuting and OnXXXExecuted. They correspond to the Action or Reuslt before and after execution. When multiple Action or Result filters exist on an Action, a filter pipeline is formed, as shown in:

  

Summary

In addition to introducing the filter functions and common filters of ASP. net mvc, this article also analyzes the process of creating and executing ASP. net mvc through code. Use ASP. net mvc built-in filter can meet the needs, such as authorization, error processing, etc., but the filter as ASP. net mvc is an important AOP extension method, which can be implemented by using filters reasonably, such as logging, performance analysis, and Action transaction execution, in addition, the system can be flexibly expanded without affecting the original code logic.

Refer:
Https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs
Http://blog.gauffin.org/2012/06/how-to-handle-transactions-in-asp-net-mvc3/

Link: http://www.cnblogs.com/selimsong/p/7839459.html

ASP. NET has no magic-directory

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.