MVC中为站点添加是否开启过滤器

主要思路

添加一个Attribute以及Filter类,在Filter中根据是否存在Attribute来判断是否跳到站点维护页。

代码实现

Attribute:

    /// <summary>
    ///  站点关闭时也可访问
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class RunWhenSitePausedAttribute : Attribute
    {

    }

Filter:

    /// <summary>
    /// 站点是否开启过滤器
    /// </summary>
    public class PauseSiteCheckFilter : IAuthorizationFilter, ITransientDependency
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.IsChildAction)
                return;

            //判断是否进入站点维护页
            if (!isEnable)//获取后台设置,如果站点关闭则进入以下判断
            {
                var context = HttpContext.Current;

                var methodInfo = filterContext.ActionDescriptor.GetMethodInfoOrNull();

                var isDefined = CanRunWhenSitePaused(methodInfo);

                if (!isDefined)
                {
                    //跳转页面
                    var url = UrlHelper.GenerateUrl(null, "PausePage", "Home", new RouteValueDictionary { { "area", "" } },
                        RouteTable.Routes, context.Request.RequestContext, true);
                    filterContext.Result = new RedirectResult(url);
                }
            }
        }

        /// <summary>
        /// 检查是否存在[RunWhenSitePaused]属性
        /// </summary>
        /// <param name="methodInfo"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        private bool CanRunWhenSitePaused(MethodInfo methodInfo, bool defaultValue = false)
        {
            if (methodInfo == null)
            {
                return false;
            }

            if (!methodInfo.IsPublic)
            {
                return false;
            }

            if (methodInfo.IsDefined(typeof(RunWhenSitePausedAttribute), true))
            {
                return true;
            }

            var classType = methodInfo.DeclaringType;
            if (classType != null)
            {
                if (classType.IsDefined(typeof(RunWhenSitePausedAttribute), true))
                {
                    return true;
                }
            }

            return defaultValue;
        }
    }
posted @ 2018-03-30 16:43  zhaok  阅读(172)  评论(0编辑  收藏  举报