Asp.net MVC 权限验证,以及是否允许匿名访问

public class CheckUserAttribute : ActionFilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext context)
        {
            if (this.IsAnonymousAction(context)) //是否允许匿名用户访问 [AllowAnonymous]
            {
                return;
            }

            if (context.HttpContext.Session["currentUserId"] == null)
            {
                    context.Result = new RedirectToRouteResult(
                    new RouteValueDictionary{
                        { "controller", "Error"},
                        { "action", "NotAuthorized"}
                    });
            }
        }

        #region private method

        private bool IsAnonymousAction(AuthorizationContext filterContext)
        {
            return filterContext.ActionDescriptor
                                 .GetCustomAttributes(inherit: true)
                                 .OfType<AllowAnonymousAttribute>()
                                 .Any();
        }

        #endregion

    }

 

posted @ 2019-07-02 10:42  leco_lin  阅读(749)  评论(0编辑  收藏  举报