Every request in Aps.net MVC (hereinafter referred to as "MVC") is assigned to the appropriate controller and corresponding behavior method to be processed, and in the back and forth of these processing, if you want to add some additional logic processing. The filter is used at this time.
There are four types of filters supported by MVC: Authorization (Authorization), Action (behavior), result (result), and exception (exception). As shown in the table below,
Filter type |
Interface |
Describe |
Authorization |
Iauthorizationfilter |
This type (or filter) is used to restrict access to a behavior method of the controller or controller |
Exception |
Iexceptionfilter |
Used to specify a behavior that the specified behavior handles a behavior method or an exception thrown in a controller |
Action |
Iactionfilter |
Processing before or after entering a behavior |
Result |
Iresultfilter |
Used to return the previous or subsequent processing of the result |
However, there are only three filters implemented by default, authorize (authorization), Actionfilter,handleerror (error handling), and various information as shown in the following table
Filter filters |
Class name |
Implementing interfaces |
Describe |
Actionfilter |
Authorizeattribute |
Iauthorizationfilter |
This type (or filter) is used to restrict access to a behavior method of the controller or controller |
HandleError |
Handleerrorattribute |
Iexceptionfilter |
Used to specify a behavior that the specified behavior handles a behavior method or an exception thrown in a controller |
Custom |
ActionFilterAttribute |
Iactionfilter and Iresultfilter |
Handling before or after processing or returning results before or after entering the behavior |
The filter described below, in addition to the above several, but also add a filter outputcache
1 Authorization Filter Authorize
1.1 Default authorize use
Now on the Internet, whether it is required to verify the location of more than, e-mail, shopping, and sometimes even spit a slot to be prompted to sign in. Some of the operations here are permitted only if the authorization is authenticated. In MVC, authorize can be used to implement. For example, a simple password change operation
[Authorize] Public actionresult ChangePassword () { return View (); }
It requires the user to pass the authorization to enter into this behavior method, otherwise hard to request that page, will only get this result
If you want to pass authentication, by calling the Formsauthentication.setauthcookie method to get authorization, the landing page is as follows
@model filtertest.models.loginmodel@{Layout=NULL;}<! DOCTYPE html>@using (Html.BeginForm ()) {<div>ID: @Html. textboxfor (M=m.username)<br/>Password: @Html. passwordfor (M=M.password)<br/> <input type="Submit"Value="Login"/> </div> } </div></body>[HttpPost]//The predicate filter is used here, only the POST request is processed . Publicactionresult Login (Loginmodel login) {if(Login. UserName = ="Admin"&& Login. Password = ="123456") {Formsauthentication.setauthcookie (login. UserName,false); returnRedirect ("/customer/changepassword"); } returnView (); }
Of course, there must be logged off, because the logout is in the login after the occurrence, no login success is not logged out, so the behavior of the logoff method also add authorize filter, logout call is the FormsAuthentication.SignOut method, the code is as follows
[Authorize] Public actionresult LogOut () { formsauthentication.signout (); return Redirect ("/customer/login"); }
1.2 Custom Authorization
We do not have to use the MVC default authorize authorization validation rules, rules can be self-defined, custom authorization filter can inherit Authorizeattribute this class, there are two methods in this class is to be rewritten
- BOOL Authorizecore (HttpContextBase HttpContext): Here is the logical processing of authorization validation, which returns true by authorization and returns False if not.
- void Handleunauthorizedrequest (AuthorizationContext filtercontext): This method is a matter of handling authorization failures.
This defines a comparison of the ride of the authorization processor, when the request is just an even minute, the authorization can be obtained, and vice versa. When the authorization fails, it jumps to the landing page.
Public classMyauthorizeattribute:authorizeattribute {protected Override BOOLAuthorizecore (HttpContextBase HttpContext) {//return base. Authorizecore (HttpContext); returnDateTime.Now.Minute%2==0 } protected Override voidhandleunauthorizedrequest (AuthorizationContext filtercontext) {filterContext.HttpContext.Response. Redirect ("/customer/login"); //base. Handleunauthorizedrequest (filtercontext); } }
[Myauthorize] Public actionresult ShowDetail () { return View (); }
Custom filters:
Controller code:
[Checklogin]//here is a custom attribute to reference the appropriate namespace PublicActionResult Index () {returnView ();} PublicActionResult Login ()//This action automatically writes the login information to the cookie.{HttpCookie Hcusername=NewHttpCookie ("username","Admin"); HttpCookie Hcpassword=NewHttpCookie ("Password","123456"); System.Web.HttpContext.Current.Response.SetCookie (Hcusername); System.Web.HttpContext.Current.Response.SetCookie (Hcpassword); returnView ();}
Filter Code:
Public classChecklogin:actionfilterattribute {//It was a bit messy before the action was executed, but it was just a matter of judging the cookie user name password. Public Override voidonactionexecuting (ActionExecutingContext filtercontext) {httpcookiecollection Cookiecollect= System.Web.HttpContext.Current.Request.Cookies;if(cookiecollect["username"] ==NULL|| cookiecollect["Password"] ==NULL) {Filtercontext.result=NewRedirectresult ("/home/login"); } Else { if(cookiecollect["username"]. Value! ="Admin"&& cookiecollect["Password"]. Value! ="123456") {Filtercontext.result=NewRedirectresult ("/home/login"); } } } }
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.
Global Filters
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.
Public Static void registerglobalfilters (globalfiltercollection filters) { filters. ADD (new Handleerrorattribute ()); // registering a global filter Filters. ADD (new Testfilterattribute () {message=" global "});
This will execute this filter for each action, without having to label each controller top.
MVC Filter Detailed