Features: MVC provides filter filters that enable developers to implement the same functionality directly with the filter without complex AOP implementations.
Implementation: 1. Define a class implementation ActionFilterAttribute, overload the method in the pretext and add the attribute on the controller or action
2. If each action is to be implemented, it can be in the global file, in the Register filter "registerglobalfilters (globalfilters.filters);" Before using the GlobalFilters.Filters.Add method to join the implementation of the defined Filter object
Example:
1. Define the filter class first
[AttributeUsage (attributetargets.all,allowmultiple=true)]//This property allows him to perform multiple Public classDemoactionattributefileter:actionfilterattribute { Public stringSTRMSG {Get;Set; } Public Override voidonactionexecuting (ActionExecutingContext filtercontext) {filterContext.HttpContext.Response.Write ( "<script>alert (' Before execution:"+strmsg+"') </script>"); Base. OnActionExecuting (Filtercontext); } Public Override voidonactionexecuted (ActionExecutedContext filtercontext) {filterContext.HttpContext.Response.Write ( c5>"<script>alert (' After execution:"+ STRMSG +"') </script>"); Base. OnActionExecuted (Filtercontext); } }
2. Use this feature
[MyMVC3Test.Filter.DemoActionAttributeFileter (STRMSG ="Hello")] Public classHomecontroller:controller {[MyMVC3Test.Filter.DemoActionAttributeFileter (STRMSG="Actionhello")] PublicActionResult Index (stringstrhome) {Viewbag.message="Welcome to ASP. NET MVC----"+Strhome; Viewbag.msg="hehe"; returnView (); } PublicActionResult About () {returnView (); } }
3. Global filter Use
protected void Application_Start () { arearegistration.registerallareas (); GLOBALFILTERS.FILTERS.ADD (new MyMVC3Test.Filter.DemoActionAttributeFileter () {strmsg=" Global " }); Registerglobalfilters (globalfilters.filters); RegisterRoutes (routetable.routes); }
The application of the MVC path with 1--filter