MVC Filter Details and examples

Source: Internet
Author: User

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> public class Myactionfilterattribute:actionfilterat Tribute {//<summary>///Before the action method///</summary>//<param name=        "Filtercontext" ></param> public override void OnActionExecuting (ActionExecutingContext filtercontext) {//1. The current request matches the routing information and the routing object in the Routedata//If the request is a controller method in a zone, you can also pass the FilterContext.RouteData.DataTo kens["area"] gets the region name//string Strarea = filtercontext.routedata.datatokens["Areas"].            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 = Filtercontex            T.actiondescriptor.actionname; String strController2 = Filtercontext.aCtionDescriptor.ControllerDescriptor.ControllerName; 2.1 Check if the requested method adds the Moneyattribute attribute if (filterContext.ActionDescriptor.IsDefined (typeof (Filters.moneyattribut                e) (false)) {//Returns the result directly for the request without executing the corresponding Action method, and does not execute onactionexcuted, but executes the result filter and the build view Filtercontext.result = new Contentresult () {Content = "<br/> hahaha, just skipped it ~~~!            <br/> "}; } filterContext.HttpContext.Response.Write ("Wow hahaha!")            Onactionexecuting<br/> "); Base.        OnActionExecuting (Filtercontext); }///<summary>///After the action method///</summary>//<param name= "Filtercont            Ext "></param> public override void OnActionExecuted (ActionExecutedContext filtercontext) { FilterContext.HttpContext.Response.Write ("Wow hahaha!")            Onactionexecuted<br/> "); Base.        OnActionExecuted (Filtercontext); }

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/>");            Viewbag.name = "Time:" + DateTime.Now;            return View ();        }

Use Method 2: Add filters to the party class

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

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

public class Filterconfig    {public        static void 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//////Before the view is loaded///</        Summary> public class MyResultFilterAttribute:System.Web.Mvc.ActionFilterAttribute {//<summary> Execute before loading "view"//</summary>//<param name= "Filtercontext" ></param> publi c override void Onresultexecuting (System.Web.Mvc.ResultExecutingContext filtercontext) {FilterContext.H            TtpContext.Response.Write ("Execute onresultexecuting <br/> before loading view"); Base.        Onresultexecuting (Filtercontext); }///<summary>///Load "view" to execute///</summary>//<param name= "Filtercontext" &G             t;</param> public override void Onresultexecuted (System.Web.Mvc.ResultExecutedContext filtercontext) {            FilterContext.HttpContext.Response.Write ("Execute onresultexecuted <br/> after loading view"); Base. Onresultexecuted (FiltercontexT); }    }

Example: Authorization filter-executes before the action filter

<summary>    //Authorization Filter-execute before the action filter///    </summary> Public    class Myauthorizeattribute: Authorizeattribute    {public        override void Onauthorization (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 filter///</summary> public class Myhandleerrorattribute: Handleerrorattribute    {public        override void Onexception (Exceptioncontext filtercontext)        {            //1. Gets the exception object            Exception ex = filtercontext.exception;            2. Record the Exception Log            //3. redirect Friendly page            filtercontext.result = new Redirectresult ("~/error.html");            4. Mark exception has been processed            filtercontext.exceptionhandled = true;            Base. Onexception (Filtercontext);        }    }




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.