• MVC常用筛选器Filter


    1.ActionFilterAttribute

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace WolfUI.Filter
    {
        public class wolfFilterAttribute : ActionFilterAttribute
        {
            //action method调用前发生。
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                Debug.WriteLine("OnActionExecuting");
            }
            //action method调用后发生, 但是在result执行前发生 (在 view 呈现前)
            public override void OnActionExecuted(ActionExecutedContext filterContext)
            {
                Debug.WriteLine("OnActionExecuted");
            }
            //result执行前发生(在view 呈现后)
            public override void OnResultExecuted(ResultExecutedContext filterContext)
            {
                Debug.WriteLine("OnResultExecuted");
            }
            //result执行前发生(在view 呈现前)
            public override void OnResultExecuting(ResultExecutingContext filterContext)
            {
                Debug.WriteLine("OnResultExecuting");
            }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace WolfUI.Filter
    {
        /// <summary>
        /// 接口参数验证过滤器
        /// author:wolf
        /// </summary>
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
        public class ModelValidationAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext actionContext)
            {
                var viewData = actionContext.Controller.ViewData;
                var modelState = viewData.ModelState;
                if (!modelState.IsValid)
                {
                    string error = string.Empty;
                    foreach (var key in modelState.Keys)
                    {
                        var state = modelState[key];
                        if (state.Errors.Any())
                        {
                            error = state.Errors.First().ErrorMessage;
                            break;
                        }
                    }
                    actionContext.Result = new JavaScriptResult() { Script = $"$tools.dangerTip('{error}','');" };
                }
            }
        }
    }

    2.HandleErrorAttribute

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace SuiBao.WebBI.Filter
    {
        public class ExceptionLogAttribute : HandleErrorAttribute
        {
            public override void OnException(ExceptionContext filterContext)
            {
                //写错误日志记录
                string url = HttpContext.Current.Request.Url.AbsoluteUri;
                string message = string.Format("异常页面:{0}
    引发异常源:{1}
    消息类型:{2}
    消息内容:{3}
    引发异常的方法:{4}
    堆栈信息:{5}"
                    , url
                   , filterContext.Exception.Source
                    , filterContext.Exception.GetType().Name
                    , filterContext.Exception.Message
                     , filterContext.Exception.TargetSite,
                     filterContext.Exception.StackTrace
                     );
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    SuiBao.Utility.LogHelper.Exception(message);
                    var reqWith = filterContext.RequestContext.HttpContext.Request.Params["X-Requested-With"];
                    //还有一种判断办法,根据报文头里的accept类型,参考权限验证里面
                    if (!string.IsNullOrEmpty(reqWith) && reqWith == "XMLHttpRequest")
                    {
                        filterContext.Result = new JavaScriptResult() { Script = "$tools.dangerTip( '系统错误,请稍候再试!');" };
                    }
                    else
                    {
                        filterContext.Result = new JsonNetResult() { Data = new { Success = false, Msg = "系统错误,请稍候再试!" } };
                    }
                }
                else
                {
                    SuiBao.Utility.LogHelper.Exception(message);
                    //根据状态码处理
                    int statusCode = new HttpException(null, filterContext.Exception).GetHttpCode();
                    if (statusCode == 500)
                    {
                        filterContext.Result = new RedirectResult("/Error/Http_500");
                        filterContext.HttpContext.Response.StatusCode = 500;
                    }
                    else if (statusCode == 404)
                    {
                        filterContext.Result = new RedirectResult("/Error/Http_404");
                        filterContext.HttpContext.Response.StatusCode = 404;
                    }
                }
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.Clear();
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    
            }
        }
    }

    3.AuthorizeAttribute

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace WolfUI.Filter
    {
        public class AuthorizeDiy : AuthorizeAttribute
        {
            /// <summary>
            /// 提供一个入口用于自定义授权检查
            /// </summary>
            /// <param name="httpContext"></param>
            /// <returns></returns>
            protected override bool AuthorizeCore(HttpContextBase httpContext)
            {
                bool pass = false;
                HttpCookie cookie = HttpContext.Current.Request.Cookies["admin"];
                if (cookie == null || cookie.Value == null)
                {
                    httpContext.Response.StatusCode = 401;
                    pass = false;
                }
                else
                {
                    pass = true;
                }
                return pass;
            }
    
            /// <summary>
            /// 处理未能授权的Http请求
            /// </summary>
            /// <param name="filterContext"></param>
            protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
            {
                base.HandleUnauthorizedRequest(filterContext);
                filterContext.HttpContext.Response.Write(filterContext.HttpContext.Response.StatusCode);
                if (filterContext.HttpContext.Response.StatusCode == 401)
                {
                    //跳转到登录界面
                    filterContext.Result = new RedirectResult("/Login");
                }
            }
        }
    }

    4.设置全局过滤

     public class FilterConfig
        {
            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                //登录验证
                filters.Add(new AuthorizationAttribute());
                //异常处理
                filters.Add(new ExceptionLogAttribute());
            }
        }
  • 相关阅读:
    策略模式
    简单工厂模式
    单例模式
    sp_xml_preparedocument _使用 处理XML文档
    LINQ to XML
    动态Linq(结合反射)
    IEqualityComparer<T>接口
    Linq to object 技巧、用法集锦
    IComparer<T> 接口Linq比较接口
    Linq to BBJECT之非延时标准查询操作符
  • 原文地址:https://www.cnblogs.com/lgxlsm/p/6728331.html
Copyright © 2020-2023  润新知