MVC Filter Details and examples

Source: Internet
Author: User
Tags httpcontext

The MVC filter is divided into four: Actionfilter (method Filter), Resultfilter (Result filter), 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>       Public classMyactionfilterattribute:actionfilterattribute {/// <summary>          ///called before the action method/// </summary>          /// <param name= "Filtercontext" ></param>           Public Override voidonactionexecuting (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 get the zone name by filtercontext.routedata.datatokens["area"//string strarea = filtercontext.routedata.datatokens["Area"].  ToString ();             stringStrcontroller = filtercontext.routedata.values["Controller"].              ToString (); stringStraction = filtercontext.routedata.values["Action"].              ToString (); //filterContext.RouteData.GetRequiredString//2. Another way to get the requested class name and method name            stringStrAction2 =FilterContext.ActionDescriptor.ActionName; stringStrController2 =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 executedFiltercontext.result =NewContentresult () {Content ="<br/> ha ha, directly skipped it ~~~! <br/>" }; } filterContext.HttpContext.Response.Write ("Wow hahaha! Onactionexecuting<br/>"); Base.          OnActionExecuting (Filtercontext); }            /// <summary>          ///called after the action method/// </summary>          /// <param name= "Filtercontext" ></param>           Public Override voidonactionexecuted (ActionExecutedContext filtercontext) {FilterContext.HttpContext.Response.Writ E ("Wow hahaha! Onactionexecuted<br/>"); Base.          OnActionExecuted (Filtercontext); }  

Use Method 1: Add the filter to the method

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

Use Method 2: Add the filter to the method

[Filters.myactionfilter]        Public class Homecontroller:controller      {      }  

Use Method 3: Add a global filter, which is added to the FilterConfig.cs

 Public class Filterconfig     {         publicstaticvoid  registerglobalfilters (globalfiltercollection filters)         {             //filters. ADD (New Handleerrorattribute ());                // 3. Add Global  filter           filters. ADD (new  Filters.myactionfilterattribute ());               Filters. ADD (new  Filters.myhandleerrorattribute ());         }     }  

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>      Public classMyResultFilterAttribute:System.Web.Mvc.ActionFilterAttribute {/// <summary>         ///Execute before loading "view"/// </summary>         /// <param name= "Filtercontext" ></param>          Public Override voidonresultexecuting (System.Web.Mvc.ResultExecutingContext filtercontext) {Filtercontext.httpcontex T.response.write ("Execute onresultexecuting before loading view <br/>"); Base.         Onresultexecuting (Filtercontext); }           /// <summary>         ///Execute after loading the "view"/// </summary>         /// <param name= "Filtercontext" ></param>          Public Override voidonresultexecuted (System.Web.Mvc.ResultExecutedContext filtercontext) {Filtercontext.httpcontext . Response.Write ("Execute onresultexecuted after loading view <br/>"); Base.         Onresultexecuted (Filtercontext); }     }  

Example: Authorization filter-executes before the action filter

/// <summary>      ///Authorization Filter-executes before the action filter/// </summary>       Public classMyauthorizeattribute:authorizeattribute { Public Override voidonauthorization (AuthorizationContext filtercontext) {filterContext.HttpContext.Response.Write ( "<br/>OnAuthorization<br/>"); //comment out the parent class method, because the Onauthorization method in the parent class invokes the ASP-AUTH mechanism! //base.  Onauthorization (Filtercontext);         }      }  

Example: Exception filter

/// <summary>      ///Exception Handling Filters/// </summary>       Public classMyhandleerrorattribute:handleerrorattribute { Public Override voidonexception (Exceptioncontext filtercontext) {//1. Get the Exception objectException ex =filtercontext.exception; //2. Logging the Exception Log//3. redirect Friendly pageFiltercontext.result =NewRedirectresult ("~/error.html"); //4. Marked exception has been processedfiltercontext.exceptionhandled =true; Base.          Onexception (Filtercontext); }      }  

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.