MVC FILTER过滤器(二)

授权过滤器:

    /// <summary>
    /// 授权过滤器
    /// </summary>
    public class TestAuthorizeAttribute:AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            filterContext.HttpContext.Response.Write("OnAuthorization<br/>");
            //注释掉父类方法,因为父类里的 OnAuthorization 方法会调用ASP.NET的授权验证机制
            //base.OnAuthorization(filterContext);
        }
    }

异常过滤器:

    public class TestHandleErrorAttribute:HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            //1.获取一场对象
            Exception ex = filterContext.Exception;
            //2.记录一场日志
            //3.重定向友好页面
            filterContext.Result = new RedirectResult("~/err.html");
            //4.标记一场已经处理完毕
            filterContext.ExceptionHandled = true;

            base.OnException(filterContext);
        }
    }

 

当然,可以在FilterConfig.cs中进行全局过滤

filters.Add(new TestAuthorizeAttribute());
filters.Add(new TestHandleErrorAttribute());

 

注:如果自定义错误页面没有自动跳转的话

需要去WebConfig配置文件中的<system.web>节点下添加

<customErrors mode="On"></customErrors>

 

posted @ 2019-02-10 00:42  蜗牛的礼物  阅读(174)  评论(0编辑  收藏  举报