MVC Filter Details and examples

Source: Internet
Author: User

original http://blog.csdn.net/ankeyuan/article/details/29624005

The MVC filter is divided into four: Actionfilter (method Filter), Resultfilter (the result filter, the feeling is not very pleasant, so call it), Authorizationfilter (authorization filter), Exceptionfilter (Exception handling filter)

Filter type Interface Default implementation Describe
Action Iactionfilter ActionFilterAttribute Run before and after the action method
Result Iresultfilter ActionFilterAttribute Run before and after the action result is executed
Authorizationfilter Iauthorizationfilter Authorizeattribute Run first, before any other filter action methods
Exception Iexceptionfilter Handleerrorattribute Run only on another filter, action method, action result popup exception

Example: Action method Filter

///<summary>  Action method Filter Class ///</summary> PublicClass Myactionfilterattribute:actionfilterattribute{  ///<summary>  Called before the action method  ///</summary>  ///<param name= "Filtercontext" ></param>  PublicOverridevoid OnActionExecuting (ActionExecutingContext filtercontext) {   1. The current request matching routing information and routing objects are saved in the Routedata   If the request is to request a controller method in a zone, you can also obtain the domain name by filtercontext.routedata.datatokens["area"   String strarea = filtercontext.routedata.datatokens["Area"]. ToString ();   String Strcontroller = filtercontext.routedata.values["Controller"]. ToString ();   String straction = filtercontext.routedata.values["Action"]. ToString ();   FilterContext.RouteData.GetRequiredString   2. Another way to get the requested class name and method name   string strAction2 = FilterContext.ActionDescriptor.ActionName;   string strController2 = FilterContext.ActionDescriptor.ControllerDescriptor.ControllerName;   2.1 Check if the requested method added Moneyattribute attribute   if (filterContext.ActionDescriptor.IsDefined (typeof (Filters.moneyattribute),False))  {    Sets the return result directly for the request without executing the corresponding Action method, and does not execute the onactionexcuted, but the result filter and the build view are executed   Filtercontext.result =New Contentresult () {Content ="<br/> ha ha, have been skipped directly ~~~! <br/> "};  }  FilterContext.HttpContext.Response.Write ("Wow hahaha!" Onactionexecuting<br/> ");   Base. OnActionExecuting (Filtercontext); }  ///<summary>  Called after the action method  ///</summary>  span class= "comment" >///<param name= "Filtercontext" ></param>  public override void onactionexecuted (actionexecutedcontext filtercontext)   {   FilterContext.HttpContext.Response.Write ( "Wow hahaha!" Onactionexecuted<br/> ");    base. OnActionExecuted (Filtercontext);  }           /span>              

Use Method 1: Add the filter to the method

[Filters.myactionfilter] //1. Adding a filter to a method   [Filters.money]  [filters.myresultfilter]  [filters.myauthorize]  Public  ActionResult Index () { Response.Write ("index method <br/>"); Time: "+ DateTime.Now; return View ();  }

Use Method 2: Add filters to the party class

[Filters.myactionfilter]      homecontroller:controller    {    }
Use Method 3: Add a global filter, which is added to the FilterConfig.cs
PublicClassFilterconfig{  public static void registerglobalfilters (globalfiltercollection filters)   { Span class= "indent" >   //filters. ADD (New Handleerrorattribute ());    //3. Adding global filters    filters. ADD (new filters.myactionfilterattribute ());    filters. ADD (new filters.myhandleerrorattribute ());  }}           /span>               

Example: Result filter

///<summary>  Result Filter Class-If you are requesting the Action method to load the view Calling methods before and after a view is loaded ///</summary> PublicClass MyResultFilterAttribute:System.Web.Mvc.ActionFilterAttribute{  ///<summary>  Execute before loading "view"  ///</summary>  ///<param name= "Filtercontext" ></param>  PublicOverridevoid Onresultexecuting (System.Web.Mvc.ResultExecutingContext filtercontext) {  FilterContext.HttpContext.Response.Write ("Execute onresultexecuting <br/> before loading view");   Base. Onresultexecuting (Filtercontext); }  ///<summary>  Execute after loading the "view"  ///</summary>  /// <param name= "Filtercontext" ></param>  public override void onresultexecuted (System.Web.Mvc.ResultExecutedContext filtercontext)   {    FilterContext.HttpContext.Response.Write ( "Load view after execution onresultexecuted <br/>");    base. Onresultexecuted (Filtercontext);  }}        /span>                

Example: Authorization filter-executes before the action filter

///<summary>  Authorization Filter-executes before the action filter ///</summary> Publicclass myauthorizeattribute:authorizeattribute { Span class= "indent" > public override void Onauthorization (AuthorizationContext filtercontext)   {    FilterContext.HttpContext.Response.Write ( "<br/>OnAuthorization<br/>");    //comment out the parent method, because the parent class The Onauthorization method invokes the ASP-AUTH mechanism!    //base. Onauthorization (Filtercontext);  }}        /span>                

Example: Exception filter

///<summary>  Exception Handling Filters ///</summary> PublicClass Myhandleerrorattribute:handleerrorattribute{  PublicOverridevoid Onexception (Exceptioncontext filtercontext) {   1. Get the Exception object  Exception ex = filtercontext.exception;   //2. Log exception logs    //3. redirect Friendly page    Filtercontext.result = new Redirectresult ( "~/error.html");   //4. Flag exception already processed    filtercontext.exceptionhandled = true; Span class= "indent" >  base. Onexception (Filtercontext);  }}        /span>                

MVC filter details and examples

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.