Go MVC Action Filter

Source: Internet
Author: User

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.

These filter types are executed in the order specified, and the Order property of the filter needs to be set if you need to control their execution sequence.

The base class for these classes is the System.Web.Mvc.FilterAttribute class, and if you need to implement a specific filter type, you can create a class that inherits the class and implement one or more iauthorization, Iactionfilter , Iresultfilter, Exceptionfilter interface.

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.

Consider an example:

[Filter1 (Order = 2)]
[Filter2 (Order = 3)]
[Filter3 (Order = 1)]
public void Index ()
{
Renderview ("Index");
}

The filter is executed in the following order: Filter3 = Filter1 = Filter2.

Introduction to Built-in filters

1OutputCacheAttribute

[OutputCache (duration=10,varybyparam= "None")]        Public ActionResult Testcache () {            viewbag.time = DateTime.Now.ToString ();            return View ();        }

The above code sets the OutputCache feature on the action method, which makes the page cache and caches for 10 seconds. The properties of the cache can also be set in Web. config

<caching>          <outputCacheSettings>              <outputCacheProfiles>                  <add name= "OutPutCache" duration= "varybyparam=" "None"/>              </outputCacheProfiles>          </outputCacheSettings>      </caching>

On the corresponding action method

[OutputCache (cacheprofile= "OutputCache")]        Public ActionResult Testcache () {            viewbag.time = DateTime.Now.ToString ();            return View ();        }

2 Authorizeattribute

This class primarily implements page membership and role management, with two attributes set in the Authorizeattribute class, namely users and roles, representing members and roles

[Authorize]        Public ActionResult testauthorize ()        {             return View ();        }

The authorize attribute is set on the above action method, which indicates that the action method can only be accessed by registered and authenticated users.

[Authorize (users= "Test1,test2")]        Public ActionResult testauthorize ()        {             return View ();        }

The above action method indicates that only the user test1,test2 can access, if the user too many, you can set these users as a type of role, by setting the role parameters to set

  [Authorize (roles= "Admin")]        Public ActionResult testauthorize ()        {             return View ();        }

The action method above indicates that only users with role admin can access it.

3 Handleerrorattribute

This class implements exception handling for related methods in the specified controller or controller in the Web site. When the [HandleError] attribute is set on an action method, an exception is automatically given to the exception handling page, and in MVC 4, the global HandleError feature has been added to the Global.asax when the project is created.

public static void Registerglobalfilters (Globalfiltercollection filters)        {            filters. ADD (New Handleerrorattribute ());        }

ActionFilterAttribute base class

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 filter class.

The terminology here is not exactly the same, technically, this class inherits Actionfitlerattribute, and it implements both the action filter and the result filter interface, but in a loose sense, in the ASP. In the 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 following are the order of execution of these methods:

OnActionExecuting (), Action Execute & Return View ()->onactionexecuted ()->onresultexecuting () Render View ()->onresultexecuted ()

To illustrate how to create a custom action filter, we create a custom action filter that records the log information for the different stages of the controller action process and displays it in the Visual Studio Output window.

 public class Loginactionfilter:actionfilterattribute {public override void onactionexecuted (Actionexecutedco            ntext filtercontext) {Log ("onactionexecuted", filtercontext.routedata); Base.        OnActionExecuted (Filtercontext); } public override void OnActionExecuting (ActionExecutingContext filtercontext) {Log ("Onactionexe            Cuting ", filtercontext.routedata); Base.        OnActionExecuting (Filtercontext); } public override void Onresultexecuted (ResultExecutedContext filtercontext) {Log ("Onresultexecu            Ted ", Filtercontext.routedata); Base.        Onresultexecuted (Filtercontext); } public override void Onresultexecuting (ResultExecutingContext filtercontext) {Log ("Onresultexe            Cuting ", filtercontext.routedata); Base.        Onresultexecuting (Filtercontext); private void Log (String methodName, Routedata routedata) {var controllernAME = routedata.values["Controller"];            var actionname = routedata.values["Action"];            var message = String.Format ("{0} Controller: {1} action: {2}", MethodName, Controllername, ActionName);        Debug.WriteLine (Message, "Action Filter Log"); }    }

Output Result:

Action filter log:onactionexecuting controller:home action:indexaction Filter log:onactionexecuted controller:home AC Tion:indexaction Filter log:onresultexecuting controller:home action:indexaction filter log:onresultexecuted controll Er:home Action:index

Go MVC Action 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.