Action filter of ASP. NET MVC

Source: Internet
Author: User
Tags types of filters

A year ago, I wrote a short article ASP. NET MVC action filters, which sorted out the resources of Action filter.ArticleDetailed description of action filter. The action filter acts as an attribute that can be applied to the Controller action (or the entire Controller) to change the action executed by the action. when applied to the entire controller, all actions on the Controller apply the same set action. Action filter can be used to process cache, verification, and error processing actions that use Declarative Programming Models for your operations.

ASP. net mvc Framework supports four different types of filters:

    1. Authorization Filters-ImplementationIauthorizationfilter interface attributes.
    2. Action Filters-ImplementationIactionfilter interface attributes.
    3. Result Filters-ImplementationIresultfilter interface attributes.
    4. Exception Filters-ImplementationIexceptionfilter InterfaceAttribute.

 

The default execution order of the filter is in the order listed above. For example, the authorization filter is always executed at the beginning, and the exception filter is always executed at the end. Of course, you can also set the filter execution sequence through the order attribute as needed.

ASP. net mvc Framework includes several action filters:

Name Description
Outputcacheattribute Similar to the outputcache command in web form. The outputcache attribute allows output by the MVC Framework cache controller.
Validateinputattribute

Similar to the validaterequest attribute in web form. By default, the MVC Framework checks HTML or other dangerous input incoming HTTP requests. If detected, an exception is thrown. Use this property to disable request verification.

Authorizeattribute Authorize attribute to perform declarative authorization checks on controller operations. This attribute can restrict the operations of users in a specific role. This attribute can be used when you create operations that should only be performed by users in the administrator role. ASP. NET membership service is used by default. If you do not use ASP. NET's membership service, you can inherit authorizeattribute and rewrite the implementation.
Validateantiforgerytokenattribute This attribute is a solution to help prevent cross-site request attacks (csrf ). It allows the authenticated http post to be user-specific in the framework. For more information, see "Use the ASP. net mvc antiforgerytoken () helper to prevent cross-site Request Forgery (CSFR )."

Authorization filter is used to verify and authorize the Controller action. For example, authorize filter is an example of filter verification;

Action filter contains logic used before or after the action is executed. For example, you can use an action filter to modify the View data returned by an action;

Result filter contains some logic for the view result of the action before and after execution. For example, you can modify a view result before the view is displayed in the browser;

Exception action is used to handle exception information. You can also use the exception filter to record error logs.

You can also create your own action filter. For example, to implement a custom verification system, you may need to create a custom action filter, you can also create a custom action filter to change the view data returned by the Controller action.

To make it easier for users to create a custom action filter, ASP. net mvc Framework provides a base class of actionfilterattribute, which implements the iactionfilter and iresultfilter interfaces and inherits the filterattribute class. Broadly speaking, in ASP. net mvc Framework, any type that implements filter is action filter.

The actionfilterattribute class can be rewritten using the following methods:

    • Onactionexecuting-called before the Controller action is executed
    • Onactionexecuted-called after the Controller action is executed
    • Onresultexecuting-called before the Controller action result is executed
    • Onresultexecuted-called after the Controller action result is executed

The execution sequence is as follows:

The following describes how to customize an action filter.CodeFrom ASP. net MVC 2 example tailspin travel, the implementation of the function is the execution time of the action, the page often needs a function of the current page execution time, this is a non-functional requirement, Asp. net MVC can be implemented using custom actionfilter. From the above introduction, we know that 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. receivettings ["timingenabled"]);
Private stopwatch timer;

Public override void onactionexecuting (actionexecutingcontext filtercontext)
{
Base. onactionexecuting (filtercontext );
If (this. timingenabled)
{
This. Timer = new stopwatch ();
This. Timer. Start ();
}
}

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;
}
}
}
}
}

Whether to enable the page execution time control through a configuration item. The code is very simple. You can use stopwatch to calculate the execution time (in milliseconds) store viewdata in viewdata ["executiontime"].
Add the following content at the end of the masterpage:

<Div id = "footer">
<% IF (viewdata. containskey ("executiontime") {%>
<P> execution time: <%: viewdata ["executiontime"] %> MS. </P>
<% }%>
</Div>

Exam

Creating custom action Filters

Understanding action Filters

ASP. MVC permission Design

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.