ASP.NET MVC 5 Filters

Filters are .NET attributes that add extra steps to the request processing pipeline. The MVC Framework supports five different types of filters. Each allows you to introduce logic at different points during request processing.

 

Authorization filters are run after the authentication filters, before action filters and before the action method is invoked. In most cases we derive class from Authorization rather than implementing IAuthorizationFilter.

    public class MyAuthorizationAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            // Write your authorization logic here
            return true;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            // Write your logic here when above authorization failed
        }
    }

Authentication filters are new in MVC version 5, they are run before any other filter, which lets you define an authentication policy that will be applied before any other type of filter is used. Authentication filters are also run after an action method has been executed but before the ActionResult is processed.

    public class MyAuthenticationAttribute: FilterAttribute,IAuthenticationFilter
    {
        private Stopwatch stopwatch = new Stopwatch();
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            stopwatch.Start();
        }

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            stopwatch.Stop();
            LoggerManager.DebugInfo.Info(string.Format("ActionMethod - Controller: {0}, Action: {1}, Elapsed Time: {2}ms (included authentication and authorization)", filterContext.RouteData.Values["controller"], filterContext.RouteData.Values["action"], stopwatch.ElapsedMilliseconds));
        }
    }

Exception filters are run only if an unhandled exception has been thrown when invoking an action method.

  • Another kind of filter (authentication, authorization, action, or result filter)
  • The action method itself
  • When the action result is executed 
    public class MyExceptionAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                var userinfo = SessionManager.UserInfo;
                LoggerManager.Exception.Error(string.Format("Login Id:{0}, IP Address:{1}, Controller:{2}, Action:{3}, Error:{4}", userinfo.LoginId, userinfo.IPAddress, filterContext.RouteData.Values["controller"], filterContext.RouteData.Values["action"], filterContext.Exception.Message), filterContext.Exception);
                filterContext.Result = new ContentResult() { Content = string.Format("exception happended, controller:{0},action:{1}<br/>Exception:{2}", filterContext.RouteData.Values["controller"], filterContext.RouteData.Values["action"], filterContext.Exception.Message) };
                filterContext.ExceptionHandled = true;
            }
        }
    }

Action filters are filters that can be used for any purpose.

    public class MyActionFilterAttribute: FilterAttribute, IActionFilter
    {
        private Stopwatch stopwatch = new Stopwatch();
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            stopwatch.Stop();
            LoggerManager.DebugInfo.Info(string.Format("ActionMethod - Controller: {0}, Action: {1}, Elapsed Time: {2}ms", filterContext.RouteData.Values["controller"], filterContext.RouteData.Values["action"], stopwatch.ElapsedMilliseconds));
        }
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            stopwatch.Start();
        }
    }

Result filters are general-purpose filters which operate on the results produced by action methods.

    public class MyResultFilterAttribute: FilterAttribute, IResultFilter
    {
        private Stopwatch stopwatch = new Stopwatch();
        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
            stopwatch.Stop();
            LoggerManager.DebugInfo.Info(string.Format("ActionResult - Controller: {0}, Action: {1}, Elapsed Time: {2}ms", filterContext.RouteData.Values["controller"], filterContext.RouteData.Values["action"], stopwatch.ElapsedMilliseconds));
        }
        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            stopwatch.Start();
        }
    }

Using Global Filters

Ordering Filter Execution

Overriding Filters

posted @ 2017-06-12 16:55  liangzi4000  阅读(206)  评论(0编辑  收藏  举报