The action Filter for ASP.

Source: Internet
Author: User

A year ago wrote a short essay, ASP. NET MVC action Filters, which organizes the resources for Action filter, which describes the action filter in detail in this article. Action filter acts as a property (Attribute) that can be applied to the controller action (or the entire controller), changing the behavior of the action, when applied to the entire controller, All actions on the controller apply the same set of action. Use the action Filter to handle caching, validation, and error handling behavior of your operations using the declarative programming model.

The ASP. NET MVC Framework supports four different types of filter:

    1. Authorization filters– implementation IAuthorizationFilter接口的属性 .
    2. Action filters– implementation IActionFilter接口的属性 .
    3. Result filters– implementation IResultFilter接口的属性 .
    4. Exception filters– Implementation IExceptionFilter接口的 properties.

The default execution order for filter is in the order of the list above. such as validation (authorization) filter is always the first execution, the exception (exception) filter is always the last execution, of course, you can also use the Order property as necessary to set the order of the filter execution.

The ASP. NET MVC Framework includes several action Filter:

Name Description
Outputcacheattribute Similar to the Web form in the OutputCache directive. The OutputCache property allows output from the MVC Framework cache controller.
Validateinputattribute

Similar to the ValidateRequest property in Web form. By default, the MVC framework will enter incoming HTTP requests for checking HTML or other dangers. If detected, an exception is thrown. Use this property to disable request validation.

Authorizeattribute The authorize property allows declarative authorization checks on the controller to be manipulated. This property can restrict the actions of users in a particular role. You can use this property when you create an action that should only be given to users in the Administrator role. The default use of the ASP. Membership service, if you do not use the ASP. Membership service, you can inherit authorizeattribute, overriding the implementation.
Validateantiforgerytokenattribute This attribute is a solution to help prevent cross-site request attacks (CSRF). It allows authentication of the HTTP POST for user-specific markup in the Framework. For more information csrfs, see " Using the ASP. AntiForgeryToken () helper to prevent cross-site request forgery (CSFR)."

Validation (authorization) filter is used to implement validation and authorization on the controller action, such as authorize filter is an example of a validation filter;

The action filter contains some logic that is used before or after the action executes. For example, you can use an action filter to modify the view data returned by the action;

The result filter contains some logic that is used before and after view result execution for the action. For example, you can modify a view result before the view is rendered to the browser;

The exception (Exception) action is used to handle exception information, and the error log can also be logged using the exception filter.

You can also create your own action filter, for example to implement a custom validation system, you might need to create a custom action filter, or when you need to change the view data returned by the controller action, You can also implement by creating a custom action filter.

To make it easier for users to create a custom action Filter,asp.net MVC Framework provides a base class ActionFilterAttribute, This class implements the Iactionfilter and Iresultfilter interfaces, and inherits the FilterAttribute class. Broadly speaking, in the ASP. NET MVC framework, any type that implements the filter is an action filter.

The ActionFilterAttribute class has the following methods to override:

    • Onactionexecuting– called before the controller action executes
    • Onactionexecuted– called after the controller action executes
    • Onresultexecuting– called before the controller action result executes
    • Onresultexecuted– called after controller action result is executed

The order of execution is as follows:

Let's show you how to customize an action Filter, the code for this example comes from the ASP. Tailspin Travel, which is the implementation time of the action, the page often needs a function of the current page execution time, This is a non-functional requirement that can be implemented using the custom Actionfilter on ASP. From the above introduction, we know we need to rewrite the onactionexecuting and onactionexecuted methods, the code is as follows:

Namespace Microsoft.Samples.Tailspin.Web { using System.Configuration; Using System.Diagnostics; using System.Globalization; using SYSTEM.WEB.MVC;

public class Executiontimingattribute:actionfilterattribute { private bool timingenabled = bool. Parse (configurationmanager.appsettings["timingenabled"]); private Stopwatch timer;

public override void OnActionExecuting (ActionExecutingContext filtercontext){              Base. OnActionExecuting (Filtercontext);               if (this.timingenabled)               { Span class= "Apple-converted-space" >                   This.timer = new Stopwatch ();                    This.timer.Start ();              }< Span class= "Apple-converted-space" >         }

public override void OnActionExecuted (ActionExecutedContext filtercontext){Base. OnActionExecuted (Filtercontext);if (this.timingenabled){This.timer.Stop ();Trace.WriteLine (String. Format (CultureInfo.InvariantCulture, "Action execution time: {0}ms", this.timer.ElapsedMilliseconds));                  if ( Filtercontext.result is ViewResult)                   {                       ((ViewResult) filtercontext.result). viewdata["ExecutionTime"] = this.timer.ElapsedMilliseconds;                   }              }         }      }  }

With a configuration item that enables page execution time control, the code is very simple, using stopwatch for time calculations, and storing the execution time (in milliseconds) in ViewData viewdata["ExecutionTime"]. at the end of the masterpage, add:

<div id= "Footer" > <% if (Viewdata.containskey ("ExecutionTime")) {%> <p>exe Cution time: <%:viewdata["ExecutionTime"]%> ms.</p> <% }%> </div> /c2>

References

Creating Custom Action Filters

Understanding Action Filters

Asp. MVC Privilege Design

The action Filter for ASP.

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.