Code explanation ASP. NET MVC Filter

Source: Internet
Author: User
Tags types of filters
This article mainly introduces the ASP. NET MVC Learning Summary of the filter details, small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.

First, Filter introduction

1.1. Understand what filters are

1, the filter (Filters) is to inject additional logic into the request processing pipeline. Provides a simple and elegant way to achieve crosscutting concerns.

2. The so-called filter (Filters), the filter inside the MVC framework is completely different from the Request.filters and Response.filter objects inside the ASP. What we call a filter is usually a filter inside the MVC framework.

3, the filter can inject some code logic into the request processing pipeline, is based on C # attribute implementation. When the class that is responsible for invoking the action Controlleractioninvoker checks the attribute on the action when the action is invoked and see if the attribute implements the specified interface for additional code injection processing

1.2. Understanding why filters are used

Suppose you do a small project, one of which is the Operations management user Information module, there is a need for user information management must be authenticated users to operate, we can check the authentication request in each action method, as follows:

using mvcfilterdmo.core;using system;using system.collections.generic;using System.Linq ; using system.web;using system.web.mvc;using system.web.security;namespace mvcfilterdmo.controllers{public class Homecontroller:controller {public ActionResult Index () {if (!      request.isauthenticated) {formsauthentication.redirecttologinpage ();    }//Operation section ... return View (); } public ActionResult Insert () {if (!      request.isauthenticated) {formsauthentication.redirecttologinpage ();    }//Operation section ... return View (); Public ActionResult Update () {if (!      request.isauthenticated) {formsauthentication.redirecttologinpage ();    }//Operation section ... return View (); } public ActionResult Delete () {if (!      request.isauthenticated) {formsauthentication.redirecttologinpage ();    }//Operation section ... return View (); }//Other Action action method//...}} 

Using the code above, you can see that there are a lot of duplication in this way to check for authentication of requests, which is why you use filters to achieve the same effect. As shown below:

Using mvcfilterdmo.core;using system;using system.collections.generic;using system.linq;using System.Web;using system.web.mvc;using system.web.security;namespace mvcfilterdmo.controllers{  [Authorize] public  class Homecontroller:controller  {public    actionresult Index ()    {      //operations Section      ... return View ();    }    Public ActionResult Insert ()    {      //operation section      ... return View ();    }    Public ActionResult Edit ()    {       //operation section      ... return View ();    }    Public ActionResult Delete ()    {      //operations Section      ... return View ();    }    Other action action method    //...  }}

Filter is. NET features (Attributes), which provides additional methods for adding to the request processing pipeline. The same effect can be achieved using the authorize filter, but the code is clearly more concise and elegant than before.

Second, the use of filters

2.1, basic type of filter

Filter implementation mechanism: Before the MVC framework invokes an action, it checks to see if an attribute (Attributes) is implemented in the definition of the method, and if so, the method defined by the attribute is called when the request processing pipeline is in place.

The ActionFilterAttribute class implements both the Iactionfilter interface and the Iresultfilter interface. This is an abstract class that requires you to provide an implementation. The Authorizeattribute and Handleerrorattribute classes contain useful features and can be used without having to create derived classes.

2.2, the application of the filter, the application method and the order of execution

Application: The filter can be applied to the controller can also be used on the action method, when applied to the control, indicating that all the action methods have this filter, and can be mixed, or multiple use, as follows:

[A]//indicates that all action methods apply a filter public class democontroller:controller{  [b]//b,c Filter only acts on this action method, but it also has a filter applied effect  [C]  Public ActionResult Index ()  {     //operation section     ... return View ();  } }

How to apply: attributes, as shown in the preceding code.

execution Order: the same type of filter, execution sequence close to the first execution of the method, different types of filters are generally executed in the order of "authorize--->action--->actionresult" As for the exception filter, An exception filter is executed whenever an exception is thrown. If you want to adjust the order of execution, you can control the order of execution by adjusting the order method value size, and the smaller the value, the better the first execution. is the execution sequence diagram of the Action/result filter application

(1), the same type of filter application example: Two custom action filter Myfirstfilter,mythreefilter applied to the same action method on index.

The three controller code is as follows:

The Myfirstfilter code is as follows:

The Mythreefilter code is as follows:

The results of the operation are as follows:

(2), different types of filter application example: There is a custom action filter myfirstfilter, there is a custom result filter mysecondfilter, applied to the same action method index.

The three controller code is as follows:

The Myfirstfilter code is as follows:

The Mysecondfilter code is as follows:

The results of the operation are as follows:

After reading the above explanations, it may be that you are now in the order of execution of these filters, and how to customize the filters do not understand, it does not matter, the following we will describe the use of these basic filters, and how to customize the filter.

2.3. Using Authorization Filter

All implementations of the Iauthorizationfilter interface can be called an authorization filter: It is defined as follows:

Public interface Iauthorizationfilter    {       void onauthorization (AuthorizationContext filtercontext);    }

Because of the authorizeattribute implementation of the MVC Framework System has some outstanding functions, and this kind of security-related code must be carefully written, so generally we do not directly implement this interface, but to inherit the Authorizeattribute class, and rewrite its Authorizecore method, signed as: BOOL Authorizecore (HttpContextBase HttpContext) while processing authorization failed, You can override its Handleunauthorizedrequest method with the signature: void Handleunauthorizedrequest (AuthorizationContext context). Note: Authentication and authorization are two different things, and authentication occurs before authorization.

The default authorization filter already has the function of verifying, and its verification mechanism is to take advantage of the authentication mechanism that comes with the ASP, such as form authentication and Windows authentication. In addition to the validation feature, it also has an authorized function. Authorization filters are the first to run in all filters.

When the route arrives at the controller, the MVC framework detects if there is an authorization filter on the relevant action before invoking the action, and if there is a call to the Onauthorization method, the corresponding action is invoked if the method approves the request.

There are several scenarios for using authorization filters:

1. Add authorize directly on the action or on the controller, indicating that authentication is enabled, but no authorization is involved.

2. Add authorize (users= "A, B")], which means that authentication is enabled and authorization is enabled, and only a or B user can access the controller.

3. When adding authorize (roles= "Admin,member")], the steps are as follows:

---take advantage of ASP. NET-brought role providers, or implement their own role providers, to implement their own role providers, only need to integrate the RoleProvider type, and implement all of these methods or part of the method, it is best to implement all methods.

---Configure the Role Manager in the Web. config file in the root directory of the application.

---Use the roles type in the appropriate action to access the related methods in the RoleProvider that you created.

Use the built-in authorization filter

The MVC framework has a built-in authorization filter, Authorizeattribute, which allows us to specify authorization policies using the two common properties of this class, as follows:

Users and Roles are also related, such as users= "A,b,c", roles= "admin", which means that the user is a,b,c one and is the admin role to access.

Create a custom authorization filter

Method One: Implement the Iauthorizationfilter interface directly, but this is not recommended because of the security-related code involved.

Way two: Inherit the Authorizeattribute class, and rewrite its Authorizecore method, signed as: BOOL Authorizecore (HttpContextBase HttpContext), the code is as follows:

public class Myauthorizeattribute:authorizeattribute  {    private string[] allowedusers;    Public Myauthorizeattribute (params string[] users)    {      allowedusers = new string[] {"admin", "user1", "XF"};    }    protected override bool Authorizecore (HttpContextBase HttpContext)    {      return HttpContext.Request.IsAuthenticated &&allowedusers.contains (HttpContext.User.Identity.Name,         stringcomparer.invariantcultureignorecase);    }  }

2.4. Use Action Filter

Action filters are multi-purpose filters that can be used for any purpose, and creating a custom action filter requires implementing the Iactionfilter interface code, which looks like this:

The interface defines two methods, and the MVC framework calls the Onactionexecting method before invoking an action method. The OnActionExecuted method is called after the action method is called.

Implementing the Onactionexecting Method

The parameter ActionExecutingContext object inherits from the ControllerContext, where the 2 properties are:

Actiondescriptor: Provides information about the action method

Result: Type ActionResult, this request can be canceled by setting a non-null value for this property.

We can use a filter to cancel a request by setting the result property. The code looks like this:

public class Myactionfilterattribute:filterattribute, Iactionfilter  {public    void onactionexecuting ( ActionExecutingContext filtercontext)    {      if (filterContext.HttpContext.Request.IsLocal)      {        Filtercontext.result = new Httpnotfoundresult ();      }    }    public void onactionexecuted (ActionExecutedContext filtercontext)    {      //not implemented    }  }

This example checks whether the request is from the local machine by using the OnActionExecuting method, and if so, the formation user returns a response that was not found by a "404". Running results such as:

Implementing the OnActionExecuted Method

We can also use the OnActionExecuted method to perform some tasks that span the action method, the following example is the time to calculate the action method run, the code is as follows:

public class Myactionfilterattribute:filterattribute, Iactionfilter  {    private Stopwatch timer;    public void onactionexecuting (ActionExecutingContext filtercontext)    {      timer = stopwatch.startnew ();    }    public void onactionexecuted (ActionExecutedContext filtercontext)    {      timer. Stop ();      if (filtercontext.exception = = null)      {        filterContext.HttpContext.Response.Write (          string. Format ("Action method delay time: {0}",            timer.) elapsed.totalseconds));}}}  

We apply the custom action filter Myactionfilter to the HomeController index method, and the result is as follows:

2.5. Using the result filter

The result filter is a multipurpose filter, he will operate the result of the action method, the result filter implements the Iresultfilter interface, the creation custom result filter needs the present Iresultfilter interface, the interface code is as follows:

When the result filter is applied to an action method, the Onresultexecuting method is called before the action method returns the result of the action, and the Onresultexecuted method is called after the result of the action is returned. The following example is the time to calculate the run of the action method return result, the code is as follows:

public class Myresultfilterattribute:filterattribute, Iresultfilter  {    private Stopwatch timer;    public void onresultexecuting (ResultExecutingContext filtercontext)    {      timer = stopwatch.startnew ();    }    public void onresultexecuted (ResultExecutedContext filtercontext)    {      timer. Stop ();      FilterContext.HttpContext.Response.Write (String. Format ("Result execution delay time: {0}", timer.) elapsed.totalseconds));}    }

We apply the custom result filter myresultfilter to the HomeController index method, and the result is as follows:

It is important to note that the action filter is run before the page output, and the result filter is run after the page output.

2.6. Use exception filter

Exception filters run only if an unhandled exception is thrown when an action method is called, and the exception comes from the following location:

A, another filter (authorization, action, or result filter).

B, the action method itself.

C, when the action result is executed.

Using the built-in exception filter

Handleerrorattribute (Handler error attribute), which is an exception filter embedded in MVC, has the following 3 important attributes:

1.ExceptionType: Type, which represents the type of exception that you want to be processed by this filter, including its subtypes, the default value is System.Exception

2.View: Type string, which represents the view page presented by this filter, the default value is error

3.Master: The master page of the rendered view page, if not specified, the view will use its default master page

The embedded handleerrorexception only takes effect when the mode setting of the customerror configured in the config file,. remoteonly, is set to on, as shown in:

This filter also passes an object of type Handleerrorinfo to the view so that the view can display some additional information about the error. The following is an example of using an exception filter.

Apply to the Index action method:

Under the Views/shared folder, add a view page specialerror.cshtml that shows the exception information, with the following page code:

@model Handleerrorinfo  <! DOCTYPE html>  

The results of the operation are as follows:

Create a custom exception filter

If we have special requirements for exception filters, which can be done with a custom exception filter, creating a custom exception filter must implement the Iexceptionfilter interface code as follows:

The Onexception method is called when an unknown processing exception occurs. The method of passing a Exceptioncontext object, derived from the ControllerContext class, defines some additional filter-specific properties as shown in the following table:

Thrown exceptions can be accessed through the Exception property. By setting the Exceptionhandled property to True, an exception filter can report that it has handled the exception, and all exception filters that are applied to an action are called.

It is important to note that if all exception filters for an action method are set to the Exceptionhandled property to the TRUE,MVC framework, the default ASP. NET exception handler will be used.

The result property has an exception filter used to tell the MVC framework what to do, and the two main applications of the exception filter are logging the exception to the log and displaying the appropriate message to the user. The following code shows the user being redirected to a specified error page by creating a custom exception filter when an unhandled exception occurs for a particular Bell class.

public class Myexectionattribute:filterattribute,iexceptionfilter  {public    void onexception ( Exceptioncontext filtercontext)    {      if (!filtercontext.exceptionhandled&&        Filtercontext.exception is NullReferenceException)      {        Filtercontext.result = new Redirectresult ("~/Content/ Specialerrorpage.html ");        filtercontext.exceptionhandled = True;}}    }

Then add a folder named content in the project root directory, under which the specierrorpage.html file is created, and when the exception is processed, the user is displayed with this error page. The code for this page is as follows:

<! DOCTYPE html>

Apply the myexection exception filter to the controller and proactively let it throw a null reference exception for testing.

public class Homecontroller:controller  {    [myexection] public    actionresult Index ()    {      throw new NullReferenceException ();    }  }

The results of the operation are as follows:

Summary: This article briefly summarizes the understanding of filters and how to use the MVC framework to build basic filters and how to customize filters and applications.

Related Article

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.