asp.net mvc filter using __.net

Source: Internet
Author: User
Tags exception handling

Turn from: http://blog.csdn.net/alex_xfboy/article/details/10255573

Filter Interface

Filter type Interface Default implementation of MVC Description
Authorization Iauthorizationfilter Authorizeattribute Executes first, before other types of filter and action methods
Action Iactionfilter ActionFilterAttribute Executes before and after the action method executes
Result Iresultfilter ActionFilterAttribute Execute before result execution and after execution
Exception Iexceptionfilter Handleerrorattribute Executes when an exception is thrown (exception occurs in Action/result/filter)
Authorization Filter Authorization Filter is the first filter in all filter types that executes before the action method call. Authorization filter needs to implement Iauthorizationfilter interface:
Public interface Iauthorzationfilter
{
     void onauthorization (AuthorizationContext context);
}
As you can see, the code that we want to implement the authorization mechanism needs to be placed in the Onauthorization method, and its parameter type AuthorizationContext inherits from ControllerContext as follows:
public class Authorizationcontext:controllercontext
 {public   

     authorizationcontext ();   

     Public AuthorizationContext (ControllerContext controllercontext, Actiondescriptor actiondescriptor);     
     Public virtual Actiondescriptor Actiondescriptor {get; set;}
     Public ActionResult result {get; set;}

 }
Authorzationcontext provides the result property and the Actiondescriptor property, the Result property represents the ActionResult that the authorization phase renders, Actiondescriptor, however, contains information about the currently executing action.
asp.net mvc provides us with a Iauthorzationfilter implementation authorizeattribute (yes, it's an attribute, inherited from FilterAttribute), This attribute can be applied to Controller and action, and it contains the roles and users attributes, specifying specific roles and users to be authorized to use. Like what:
public class Homecontroller:controller
{
     [Authorize (Users = "Zhang, zheng", Roles = "admin")] public
     Action Result Index ()
     {return
          View ();
     }
}
The above code indicates that only users who are Zhang,zheng and have role admin can be authorized to perform the index Action.

Exception Filter
When an unhandled exception is thrown, Exception filter is executed. Exception filter needs to implement Iexceptionfilter interface:
Public interface Iexceptionfilter
{
     void onexception (Exceptioncontext filercontext);
}
Exceptioncontext also inherits from ControllerContext, which provides the following additional attributes:
Property name Type Describe
Actiondescriptor Actiondescriptor Provides information about the action that is currently executing
Result ActionResult The ActionResult that Exception filter presents
Exception Exception Unhandled exception
Exceptionhandled bool Indicates whether another filter has handled this exception
Exceptionhandled is a very important attribute. In general, when a exception filter executes, we first need to check the Exceptionhandled property, if true, to indicate that another filter has handled the exception and does not need to be processed again. In order to avoid overwriting the exception that other filter solves. If False, the exception is processed appropriately, and the Exceptionhandled property is set to true after processing. By default, if the Exceptionhandled property is set to True without exception filter, asp.net MVC uses the default exception handling, which displays the exception page that we often see. The Action filter action filter can be used for any purpose, and it needs to implement the Iactionfilter interface:
Public interface Iactionfilter
{
     void onactionexecuting (ActionExecutingContext filtercontext);
     void onactionexecuted (ActionExecutedContext filtercontext);
}
As the name suggests, the OnActionExecuting method is called before the action method executes, and the OnActionExecuted method is invoked after the action method executes. We can see that the parameter filtercontext of the OnActionExecuting method is ActionExecutingContext, which also inherits from ControllerContext,   The result attribute and the Actiondesciptor property are provided in addition, and their effect is described in the previous article. Similarly, the parameter filtercontext of the OnActionExecuted method is ActionExecutedContext, inherits from the ControllerContext, and provides the result property in addition to the   The Actiondescriptor property and the Exception property (an unhandled exception thrown by the action method). To say nothing, take a look at an example:
     public class Customeractionattribute: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 ("<div>action Execution Time:{0}</div>", timer.) elapsed.totalseconds));}}
    
     public class Homecontroller:controller
     {
        [customeraction] public
        viewresult Index ()
        {
            return View ();
        }

    

Execution results:

Result filter result filter is similar to action filter, but it is performed before and after ActionResult execution, and the result filter needs to implement the Iresultfilter interface:

Public interface Iresultfilter
{
     void onresultexecuting (ResultExecutingContext filtercontext);
     void onresultexecuted (ResultExecutedContext filtercontext);
}
ActionFilterAttribute asp.net mvc provides actionfilterattribute, an abstract class that inherits FilterAttribute, Implement Iactionfilter and Iresultfilter interfaces:
Public abstract class Actionfilterattribute:filterattribute, Iactionfilter, iresultfilter
{public
     virtual void OnActionExecuting (ActionExecutingContext filtercontext)
     {
     }

     Pub
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.