mvc添加全局过滤器

目录结构

 【FilterConfig.cs】

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AA.App_Start
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());

            // 加上这个,就会对所有的Controller的方法执行LoginRequestFilter校验
            filters.Add(new LoginRequestFilter() { IsCheck = true });
        }
    }
}

【LoginRequestFilter.cs】

using AA.Common;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AA.App_Start
{
    /// <summary>
    /// 全局登录校验
    /// </summary>
    public class LoginRequestFilter : ActionFilterAttribute
    {
        public bool IsCheck { get; set; } = true;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (IsCheck)
            {
                if (HasLogin(filterContext))
                {
                    base.OnActionExecuting(filterContext);
                }
                else
                {
                    filterContext.HttpContext.Response.Redirect("/Account/Login");
                }
            }
            else
            {
                var controllerName = ((ReflectedActionDescriptor)filterContext.ActionDescriptor).ControllerDescriptor.ControllerName;
                var actionName = ((ReflectedActionDescriptor)filterContext.ActionDescriptor).ActionName;

                if (controllerName == "Account" && actionName == "Login" && HasLogin(filterContext))
                {
                    filterContext.HttpContext.Response
                        .Redirect("/index.html?P_Name=" + HttpContext.Current.Session[GlobalString.P_Name]);
                }
                else
                {
                    base.OnActionExecuting(filterContext);
                }
            }
        }

        private bool HasLogin(ActionExecutingContext filterContext)
        {
            HttpContextBase httpContext = filterContext.HttpContext;

            // 只要任意一个为空,则说明用户未登录
            return !GlobalString.LoginUserProperties.Any(i => string.IsNullOrWhiteSpace(httpContext.Session[i] + ""));
        }
    }
}

Global.asax 中进行注册

using AA.App_Start;
using System.Web.Mvc;
using System.Web.Routing;

namespace AA
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}
原文地址:https://www.cnblogs.com/lishidefengchen/p/14442500.html