.Net MVC中定義全域性過濾器及在Action中排除全域性過濾器

怒彬發表於2018-07-19

1,定義過濾器:

public class LoginJsonFilter : ActionFilterAttribute
    {
        public bool IsCheck { get; set; }//
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if(!IsCheck)
            {
                return;
            }

            User user = filterContext.RequestContext.HttpContext.Session["CurrentUser"] as User;

            if (user == null)
            {
                if (IsAjax())
                {
                    Result<bool> result = new Result<bool>();
                    result.Code = ResultCode.Failed;
                    result.Message = "未登入或者登入已經過期,請重新登入";
                    filterContext.Result = new JsonResult<Result<bool>>
                    {
                        Data = result,
                        ContentType = null,
                        ContentEncoding = null,
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                    return;
                }
                else
                {
                    filterContext.Result = new RedirectResult("/User/LoginView");
                    return;
                }
            }
            else
            {
                base.OnActionExecuting(filterContext);
            }
        }

        #region 是否是Ajax請求 + static bool IsAjax()
        /// <summary>
        /// 是否是Ajax請求
        /// </summary>
        /// <returns></returns>
        public static bool IsAjax()
        {
            return HttpContext.Current.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
        }
        #endregion
    }

2,在App_Start資料夾下新增FilterConfig類

 public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new LoginJsonFilter(){ IsCheck = true});
        }
    }

3,在Global.asax中註冊全域性過濾器

 protected void Application_Start()
        {
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        }

4,如果某Action中不想使用該過濾器,如登入頁,則可以通過如下方式排除

[LoginJsonFilter(IsCheck =false)]
        public ActionResult LoginView()
        {
            return View();
        }

 

相關文章