Go MVC's Custom filter (filter)

Source: Internet
Author: User
Tags httpcontext setcookie

This article transferred from: http://www.cnblogs.com/kissdodog/archive/2013/01/21/2869298.html

One, custom filter

The custom filter needs to inherit the ActionFilterAttribute abstract class, overriding the methods required in it, and taking a look at the method signature of the ActionFilterAttribute class.

 //Represents the base class for all actions-filter attributes. [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, inherited = True, AllowMultiple = false)] public abstract class Actionfilterattribute:filter        Attribute, Iactionfilter, Iresultfilter {protected actionfilterattribute ();        //is called by the MVC framework after the action is executed.        public virtual void onactionexecuted (ActionExecutedContext filtercontext);        //is called by the MVC Framework before action executes.        public virtual void onactionexecuting (ActionExecutingContext filtercontext);        //is called by the MVC framework after the result is executed.        public virtual void onresultexecuted (ResultExecutedContext filtercontext);        //is called by the MVC framework before execution of result.    public virtual void onresultexecuting (ResultExecutingContext filtercontext); }

So the custom filter can choose the appropriate method to rewrite the square. Here is a simple example: check the login status of the filter, no login to jump to the login page

Controller code:

        [Checklogin] ///Here is a custom attribute, to reference the appropriate namespace public        ActionResult Index ()        {            return View ();        }        Public ActionResult Login () //This action automatically writes the login information to the cookie        {            HttpCookie hcusername = new HttpCookie (" Username "," admin ");            HttpCookie Hcpassword = new HttpCookie ("Password", "123456");            System.Web.HttpContext.Current.Response.SetCookie (hcusername);            System.Web.HttpContext.Current.Response.SetCookie (Hcpassword);            return View ();        } 

Filter code

    public class Checklogin:actionfilterattribute    {        //Before the action is executed, it is just a matter of judging the cookie user name password is incorrect. Public        override void OnActionExecuting (ActionExecutingContext filtercontext)        {            HttpCookieCollection cookiecollect = system.web.httpcontext.current.request.cookies;if (CookieCollect[" Username "] = = NULL | | cookiecollect["password"] = = null)            {                Filtercontext.result = new Redirectresult ("/home/login");            }            else            {                if (cookiecollect["username"]. Value! = "Admin" && cookiecollect["password"]. Value! = "123456")                {                    Filtercontext.result = new Redirectresult ("/home/login")                ;        }    }} //This example is convenient, the action to jump to is placed under the same controller, if the filter is placed on the top of the controller class, you will never jump to this loginaction. 

The effect of this filter is to jump to the login page when the user name and password are incorrect in the user's cookie, and note that the filter can also be placed at the top of the entire controller class, indicating that all actions under the controller perform the check. In this way, the code in the controller is very beautiful, and no action is filled with the code to determine the login.

Second, the custom Filte with parametersR

First of all, add a custom filter according to the previous method of adding a custom filter, but there is one more attribute in it, the code is as follows:

    PublicClassFilterattribute:actionfilterattribute {PublicString Message {GetSet; }PublicOverridevoidOnActionExecuting (ActionExecutingContext filtercontext) {Base. OnActionExecuting (Filtercontext); FilterContext.HttpContext.Response.Write ("Before action executes"+ Message +"<br/>"); }PublicOverridevoidonactionexecuted (ActionExecutedContext filtercontext) {Base. OnActionExecuted (Filtercontext); FilterContext.HttpContext.Response.Write ("After action executes"+ Message +"<br/>"); }PublicOverridevoidOnresultexecuting (ResultExecutingContext filtercontext) {Base. Onresultexecuting (Filtercontext); FilterContext.HttpContext.Response.Write ( " " + Message + <br/>" ); } public override void< Span style= "color: #000000;" > onresultexecuted (ResultExecutedContext filtercontext) {base. Onresultexecuted (Filtercontext); FilterContext.HttpContext.Response.Write ( " return result " <br/>);}}   

Then, when the filter is called, add the parameter, the controller code is as follows:

        [Filter (message= "Liu Bei")] //parameters to the upper        Public  ActionResult Index ()        {            return View ();}    

The output results are as follows:

  

If the label hits the controller, the Testfilterattributefilter will act on all actions under the controller.

by default, when a custom label is hit on the action, the label is also on the controller, but only the label on the action works. Add: If the action does not hit the tag, the tag on the controller will be executed.

What if you want the tag on the action to execute once, and then the tag on the controller executes once, then what should you do?

we only need to mark the definition of the FilterAttribute class [AttributeUsage (AttributeTargets.All, AllowMultiple = True)] to "The top red font section of the class below", That is, make it an action that can be executed more than once. the code is as follows:

    [AttributeUsage (Attributetargets.all,allowmultiple = true)]     class Filterattribute:actionfilterattribute    {        set;} ...   
third, global filter

  Sometimes we think that some public methods need to be executed by each action, but do not want to be on each controller on the action tag, what to do? Fortunately, ASP. Net MVC3 brings a nice thing to the global filter. And how to register the global filter? The answer is in the Global.asax. Let's look at the following code, how I registered the Testfilterattribute we defined above into the global filter.

     void registerglobalfilters (globalfiltercollection filters)        {            filters. ADD (new// register global filter filters. ADD (new Testfilterattribute () {message=" global "});        

This filter executes for each action, without having to label each controller top.

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.