ASP. NET MVC Learning Filter article (2)

Source: Internet
Author: User
Tags httpcontext

Below we continue with the previous ASP. NET MVC Learning Filter article (1) to learn.

3. Action Filter

As the name implies, this filter responds to calls before the action method is called. We can change the action of the actual call before the call, or we can change the result of the final return after the action call is complete, of course, many people must not quite understand what this can do,

Let's give a more practical example:

Believe that you understand the security of the site must know the cross-site request (CSRF specific can Baidu, here I do not explain), of course, there is a solution, that is, to add a code to the page, when the page to make a POST request, first to determine whether the identification code is correct,

If it is correct, continue with the operation. and reassign a new identifier after execution (or, of course, only one identifier until the end of the session), which makes it more difficult to make cross-site requests. And the life cycle of the action filter exactly matches,

Let's start writing this filter class.

First we create a new Viewmacfilterattribute class in the Filter folder, and this class needs to inherit FilterAttribute, but also to implement Iactionfilter Interface:

 1 Namespace Mvcstudy.filter 2 {3 public class Viewmacfilterattribute:filterattribute, Iactionfilter 4 { 5 6 public void onactionexecuted (ActionExecutedContext filtercontext) 7 {8 String viewmac = Guid.NewGuid (). ToString (); 9 filtercontext.httpcontext.session["Vmac"] = viewmac;10 FilterContext.Controller.ViewBag.ViewMac             = viewmac;11}12 public void onactionexecuting (ActionExecutingContext filtercontext) 14 {15 Object Viewmac = filtercontext.httpcontext.session["Vmac"];16 string strmac = Filtercontext.httpcontex t.request.form["Viewmac"];17 filtercontext.result = new Httpnotfoundresult (); if (Viewmac! = nul                     L && Strmac! = null) (Viewmac.equals (STRMAC)) 21 {22 Filtercontext.result = null;23}24}25}26}27} 

Here we implement the onactionexecuted method and the onactionexecuting method in the Iactionfilter interface, which correspond to the end of the action execution and the execution of the action, respectively. Through the code in onactionexecuting , we can clearly see that we first get the identification number from the Session , and then get the client's identification code from the form on the page,

Here we can see that the result we return by default is 404, and if histograms succeeds it sets result to null, and if result is null , the corresponding activity is called normally. Then the function in the onactionexecuted method is simply to reassign an identifier and save it in the Session .

Note: This method causes a page to post a request after the identification code is transformed. The submission of other pages fails, so there is also Ajax to assist, or a user session to assign an identification code until the end of the user session.

With this filter we can do the actual test, first we write the following code in the Home controller , and views/home under the new index.cshtml and list.cshtml, where the pages in list.cshtml are as follows:

1 @{2     viewbag.title = "List"; 3} 4  5 

Then there is the Home Controller:

1 namespace mvcstudy.controllers 2 {3 Public     class Homecontroller:controller 4     {5         [mobilresultfilter] 6
   public ActionResult Index () 7         {8  9             return View ();         }11 public         actionresult List ()         The             string viewmac = Guid.NewGuid (). ToString ();             session["vmac"] = viewmac;17             Viewbag.viewmac = viewmac;18             return View ();         }20 21         [viewmacfilter]22         [httppost]23 Public         ActionResult List (String action) with         {             return View ();         }27     }28}

Here we can see the default list action will be assigned to the code, and the POST request the corresponding list method with the filter we wrote earlier, now we can open the page and then submit, we will find just refresh, and then we put list.cshtml in the @html.hidden ("Viewmac", (string) viewbag.viewmac) deleted, re-enter this page, click Submit, you can find that there are 404 errors, This way, we can prevent cross-site requests.

4. Result filter

The above is only the action filter, after the execution of the action will return a result, even here, we can still modify the final result, before the router part of the time, once an example, is based on useragent to determine whether the cell phone, and jump to the corresponding controller under the corresponding action. But most of the time the mobile phone page and the PC page data is the same, if as before will lead to duplication of code, then we can use the result filter, after the execution of the action, determine whether the phone to change the final rendered view.

Below we continue to create a new Mobilresultfilterattribute class under the Filter folder, and this class still inherits FilterAttribute, and also implements Iresultfilter Interface, the implementation code is as follows:

1 namespace Mvcstudy.filter 2 {3 Public     class Mobilresultfilterattribute:filterattribute, Iresultfilter 4     {5< C2/>6 public         void onresultexecuted (ResultExecutedContext filtercontext) 7         {8  9         }10         one public void Onresultexecuting (ResultExecutingContext filtercontext)         {             if ( FilterContext.HttpContext.Request.UserAgent.Contains ("Android"))                 ((ViewResult) Filtercontext.result). ViewName = "List";             }17         }18     }19}

In order to be able to explain in the simplest way, so the author only judge whether useragent contains Android, if it has to modify the final view name, so that we can be implemented by annotation properties, It does not need to be placed in the controller or judged in action.

We still want to test the main, we still use the Home Controller:

1         [mobilresultfilter]2 public         ActionResult Index () 3         {4 5             return View (); 6         }

First we access it in a normal way and then let Chrome simulate the phone, so we can see that the final page will be list instead of index .

The above 3 and 4 we have to inherit the corresponding interface, but also to inherit the FilterAttribute class, in fact, ASP. NET MVC has already written for us a default class, that is ActionFilterAttribute, the definition in our source code:

1 public abstract class Actionfilterattribute:filterattribute, Iactionfilter, Iresultfilter

It has inherited the FilterAttribute, but also implemented the Iactionfilter and iresultfilter interface, so you can write down some key names.

5. No annotation attribute filter and global filter

Through the previous points, you can find that we are all using the annotation properties of the way to filter, and other we can also be directly implemented in the controller, such as the following code:

 1 namespace mvcstudy.controllers 2 {3 public class Homecontroller:controller 4 {5 protected override void onactionexecuted (ActionExecutedContext filtercontext) 6 {7 base. OnActionExecuted (Filtercontext);             8} 9 protected override void OnActionExecuting (ActionExecutingContext filtercontext) 11 {12 Base. OnActionExecuting (filtercontext);}14 protected override void Onauthorization (AuthorizationContext fi Ltercontext) (base). Onauthorization (filtercontext),}19 protected override void Onexception (Exceptioncontext Filtercontex T) {base. Onexception (filtercontext);}24 protected override void Onresultexecuted (ResultExecutedContext filter Context) (base).  Onresultexecuted (Filtercontext);}29-protected override void Onresultexecuting (ResultExecutingContext FiltercontexT) {base.         Onresultexecuting (Filtercontext);}34 [mobilresultfilter]36 public ActionResult Index () 37 {}41 return View (), ActionResult List () () Ring Viewmac = Guid.NewGuid (). ToString (); session["Vmac"] = viewmac;47 Viewbag.viewmac = viewmac;48 return View ();         }50 [viewmacfilter]52 [httppost]53 Public ActionResult List (string action) 54 {return View (); 56}57}58}

We can see that the controller has actually implemented all of the above interfaces, of course, I recommend the use of annotation properties, so as to isolate the focus, the controller code will be very messy.

The only difference about global filters is that we need to use the registerglobalfilters method in the Filterconfig class Filters.add Adding the filters we wrote above is not very special (filterconfig in App_start, this file is only available in ASP. 4 above )

6. Built-in filter

About the built-in filter we list the following here, because we are quick to get started.

Requirehttps forcing the use of HTTPS protocol to actions

OutputCache caches the output of an action method

ValidateInput Security-related authorization filters

Asynctimeout/noasynctimeout for asynchronous controllers

childactiononly can only be called as a child operation

So far, the filter section is over.

Transferred from: http://www.cnblogs.com/yaozhenfa/p/asp_net_mvc_filter_2.html

ASP. NET MVC Learning Filter article (2)

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.