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

转载于:https://www.cnblogs.com/liangzi4000/p/6854548.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值