Asp. NET no magic--asp.net MVC Filters (filter)

Source: Internet
Author: User

The previous article introduced the use of the authorize feature to implement authorization for Controller or action in ASP. This feature is actually part of the MVC feature called Filter, which is a slice-oriented programming (AOP) Implementation, this chapter introduces the filters in ASP.

Filters and their types in ASP.
Filters commonly used in ASP.
Application method of ASP-Net MVC filter
The invocation of the ASP. NET MVC action method and the execution of the filter
Creation and acquisition of ASP. NET MVC Filter
Pipeline execution for ASP. NET MVC action and result filter

Filters and their types in ASP.

In the previous Entity Framework article, which introduced the EF-band Interceptor (interceptors) feature, the filter in ASP. NET MVC is also a facet-oriented (AOP) programming method, as is the case with interceptors. is a programming way to extend an application without modifying the source code. General AOP is used to handle logging, performance statistics, security controls, transaction processing, exception handling, and other functions that do not modify the original business data.
in ASP. NET MVC, the filters are divided into the following categories, each of which is defined by a corresponding interface:
Authentication Filter (Iauthenticationfilter): This filter is added in MVC5, which is the highest priority in all filters, using the authentication filter can be an action, The controller or all controllers add authentication logic. The core of the authentication filter is to create a principal object based on the requested information (note: Authentication using identity is actually creating a Principal object), The following is the definition of iauthenticationfilter:

  

Where the authentication context has a IPrincipal property:

  

Authorization Filter (Iauthorizationfilter): Authorization filters are used to handle the access restrictions of the controller and the action.
Action method Filter (Iactionfilter): The action filter can be used to add logic before and after the action method executes.
Result Filters (iresultfilter): Result filters can add logic before and after the results are executed. (Note: The action in ASP. NET MVC returns the result as a actionresult type, which defines an execution method Executeresult, and the execution of the result is actually the processing of the returned result)

  

For example, Fileresult's execution actually adds the appropriate parameters to the HTTP response header and then writes the file's binary data to the response body, which is equivalent to the file's download function.

  

More results are described in the following articles.

Exception filter (Iexceptionfilter): An exception filter is a filter that is used to add exception handling logic when an action method throws an exception during execution.

Filters commonly used in ASP.

The categories of filters are described above, and now describe what filters are commonly used under each category:
Authentication Filter (Iauthenticationfilter): Because the authentication process can be done using mature components such as identity, the authentication filter temporarily does not find a suitable filter to use. Customizable if the system needs to be customized.
Authorization Filter (Iauthorizationfilter):
0Authorize: User authorization based on user name, role.
0RequireHttps: HTTPS-based access authorization.
0validateinput:asp.net MVC verifies that the request information contains illegal information such as HTML before execution to avoid XSS attacks, but sometimes the need is to submit HTML data. You can use this filter to set Enablevalidation to FALSE,MVC when you submit this data to skip data validation.
0ValidateAntiForgeryToken: This filter can generate anti-counterfeiting tokens for htmlhelper antiforgerytoken methods to avoid CSRF cross-site forgery attacks.
Action Filter (Iactionfilter): Custom implementations are generally based on requirements.
Exception filter (Iexceptionfilter):
0HandleError: Used to handle exceptions thrown by the action method (the default MVC template adds a global HandleError filter).

It is also important to note that the controller in ASP. NET MVC is actually a filter because the Controller base class implements all the filter interfaces:

  

So if there is a special processing requirement in a controller, there is no need to define a filter and implement the method of overloading the corresponding filter in the controller:

  

Application method of ASP-Net MVC filter

filters in ASP. NET MVC can be used in several ways:
1. Use attributes to mark the Controller and action, but be aware that filters that are used in an attribute need to be encapsulated as a single filter in addition to the corresponding filter interface. NET features and implement the Imvcfilter interface, the most convenient is to directly inherit the FilterAttribute type implementation, such as:

  

2. Add a filter through the Global filter table so that the added filter will take effect on all Controller's action methods.

  

3. The controller type is implemented by overloading the corresponding filter method, which shows that the controller itself is a type that implements all the filters.

The invocation of the ASP. NET MVC action method and the execution of the filter

The filter is executed during the action method execution, so first understand the action execution process, in the previous article introduced the controller creation and execution of the ASP. NET does not have the Magic--asp.net MVC controller instantiation and execution, and here is based on this article, to the action of the execution process is introduced, Controller execution is done through the Executecore method of the controller type:

  

You can also see from the code that the controller's execution actually invokes the execution of the action method by Actioninvoker, based on the name of the action, which in ASP. NET MVC uses a default name of Asynchronous action Invoker for Asynccontrolleractioninvoker:

  

It inherits the synchronous Controlleractioninvoker type in addition to the asynchronous function, which is primarily to improve throughput of request processing, where the synchronous version of the code is used to perform an introduction to the action and filter.

Controlleractioninvoker:

   

The following points can be seen from the code definition:
1. Its core approach is invokeaction, which handles all filter and action method invocation processing logic.
2. Getfilters method, which is used to obtain all relevant filters.
3. Invokeactionmethodwithfilters, Invokactionresultwitherfilters, Invokeauthenticationfilters, Invokeauthenticationfilterschallenge, Invokeauthorizationfilters, Invokeexceptionfilters and other related methods are used to invoke the corresponding type of filter execution method.
Here we introduce the process of filter execution in Actioninvoker by means of source analysis:

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"/>parameter 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.</exception>9          Public Virtual BOOLInvokeaction (ControllerContext ControllerContext,stringactionname)Ten         { One             if(ControllerContext = =NULL) A             { -                 Throw NewArgumentNullException ("ControllerContext"); -             } the             if(string. IsNullOrEmpty (actionname) &&!ControllerContext.RouteData.HasDirectRouteMatch ()) -             { -                 Throw NewArgumentException (Mvcresources.common_nullorempty,"ActionName"); -             } +Controllerdescriptor Controllerdescriptor = This. Getcontrollerdescriptor (controllercontext); -Actiondescriptor Actiondescriptor = This. Findaction (ControllerContext, Controllerdescriptor, ActionName);//get description of action based on controller information and action name +             if(Actiondescriptor! =NULL) A             { atFilterInfo filters = This. Getfilters (ControllerContext, actiondescriptor);//Get all Filters -                 Try -                 { -Authenticationcontext Authenticationcontext = This. Invokeauthenticationfilters (ControllerContext, filters. Authenticationfilters, Actiondescriptor);//Call Authentication Filter -                     if(Authenticationcontext.result! =NULL) -                     { inAuthenticationchallengecontext Authenticationchallengecontext = This. Invokeauthenticationfilterschallenge (ControllerContext, filters. Authenticationfilters, Actiondescriptor, authenticationcontext.result); -                          This. Invokeactionresult (ControllerContext, Authenticationchallengecontext.result??authenticationcontext.result); to                     } +                     Else -                     { theAuthorizationContext AuthorizationContext = This. Invokeauthorizationfilters (ControllerContext, filters. Authorizationfilters, Actiondescriptor);//Invoke Authorization Filter *                         if(Authorizationcontext.result! =NULL) $                         {Panax NotoginsengAuthenticationchallengecontext authenticationChallengeContext2 = This. Invokeauthenticationfilterschallenge (ControllerContext, filters. Authenticationfilters, Actiondescriptor, authorizationcontext.result); -                              This. Invokeactionresult (ControllerContext, Authenticationchallengecontext2.result??authorizationcontext.result); the                         } +                         Else A                         { the                             if(controllerContext.Controller.ValidateRequest)//To determine if a validation request is required, use the ValidateInput attribute and set Enablevalidation to false when skipping validation +                             { - controlleractioninvoker.validaterequest (controllercontext); $                             } $idictionary<string,Object> parametervalues = This. Getparametervalues (ControllerContext, actiondescriptor); -ActionExecutedContext ActionExecutedContext = This. Invokeactionmethodwithfilters (ControllerContext, filters. Actionfilters, Actiondescriptor, parametervalues);//Execute action Filter and action method -Authenticationchallengecontext AUTHENTICATIONCHALLENGECONTEXT3 = This. Invokeauthenticationfilterschallenge (ControllerContext, filters. Authenticationfilters, Actiondescriptor, actionexecutedcontext.result); the                              This. Invokeactionresultwithfilters (ControllerContext, filters. Resultfilters, Authenticationchallengecontext3.result?? Actionexecutedcontext.result);//Execute result filter and result -                         }Wuyi                     } the                 } -                 Catch(ThreadAbortException) Wu                 { -                     Throw; About                 } $                 Catch(Exception Exception) -                 { -Exceptioncontext Exceptioncontext = This. Invokeexceptionfilters (ControllerContext, filters. Exceptionfilters, exception);//exception filter is executed when an exception is caught -                     if(!exceptioncontext.exceptionhandled)//If the exception filter does not handle the exception, it continues to throw an exception A                     { +                         Throw; the                     } -                      This. Invokeactionresult (ControllerContext, exceptioncontext.result); $                 } the                 return true; the             } the             return false; the}
View Code

The following conclusions are drawn from the analysis of the above code:
1. After finding the real action method through the controller context and the action information, get all the filters.
2. Perform the authentication filter first.
3. Execute the authorization filter after the authentication filter.
4. After the authorization filter is passed, execute the action filter and the action method.
5. Execute the result filter and result.

Creation and acquisition of ASP. NET MVC Filter

According to the above introduction, you can use the global filter, the attribute tag and the overloaded controller filter method of the three ways to apply the filter, then in the execution process is how to create and obtain them through the Actioninvoker Getfilters method?
Filter provider (filterprovider): ASP. NET MVC has a filter provider concept and the actual object, it has three kinds of implementations corresponding to the above three ways of application:
0GlobalFilterCollection: Used to save the global filter instance, you can directly through it to add and get filter instances, the filter created by the scope of Gobal, can be created by the order parameter to determine the global filter execution order:

  

0FilterAttributeFilterProvider: Filter feature provider that creates filters by locating the controller and the attributes on the action, dividing the scope into a controller and an action based on the attribute marker position, When you apply an attribute, you can set the attribute's Order property to determine the order in which the filter is executed:

    

0ControllerInstanceFilterProvider: Controller instance filter provider, which is used to get the filter for the current controller instance, and the filter scope is first:

    

Filter Provider Collection (filterprovidercollection): It contains all of the filter providers mentioned above, and actioninvoker it to get all the relevant filters:

  

Fitlerprovidercollection gets the filter by obtaining all relevant filters through the above three providers and sorting the filters according to scope and order to determine the order of the filter execution.

Pipeline execution for ASP. NET MVC action and result filter

There are two methods in the definition of action and result filters, namely onxxxexecuting and onxxxexecuted, which correspond to the action or reuslt before and after execution. When there is more than one action or result filter on an action, a filter pipeline is formed, as shown in the following way:

  

Summary

In addition to introducing the filter function and common filter of ASP, this paper analyzes the process of creation and execution through the form of code. In general projects, the use of ASP. NET MVC filters can be used to meet the requirements, such as authorization, error handling, but filters as an important AOP extension in ASP, reasonable use of filters can be implemented, such as logging, performance analysis, Action's transaction execution (http://blog.gauffin.org/2012/06/how-to-handle-transactions-in-asp-net-mvc3/, This article uses the action filter to implement the database transaction, and so on, and can flexibly extend the system without affecting the original code logic.

Reference:
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/

This article link: http://www.cnblogs.com/selimsong/p/7839459.html

Asp. NET no magic--Directory

Asp. NET no magic--asp.net MVC Filters (filter)

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.