MVC巧用枚举做权限管理

用户数据表,每个用户有一个或者多个权限,用户表如下

userid,roleid,username等

权限枚举如下:

public class CustomEnum
    {
        [Flags]
        /// <summary>
        /// 用户角色枚举
        /// </summary>
        public enum UserRole
        {
            /// <summary>
            /// 游客
            /// </summary>
            Visitor = 1,
            /// <summary>
            /// 学生
            /// </summary>
            Student = 2,
            /// <summary>
            /// 老师
            /// </summary>
            ///
            Teacher = 4,
            /// <summary>
            /// 家长
            /// </summary>
            Parents = 8,
            /// <summary>
            /// 加盟商
            /// </summary>
            Agents = 16
        }
    }

为以下对象权限对象赋值

  /// <summary>
        /// 用户角色
        /// </summary>
        public static CustomEnum.UserRole UserRole
        {
            get
            {
                if (!string.IsNullOrEmpty(SessionAction.ReadSession("xxb_WebUserRole")))
                {
                    return (CustomEnum.UserRole)Enum.Parse(typeof(CustomEnum.UserRole), SessionAction.ReadSession("xxb_WebUserRole"));
                  }
                else
                {
                    return CustomEnum.UserRole.Visitor;
                }
            }
            set
            {
                System.Web.HttpContext.Current.Session["xxb_WebUserRole"] = (CustomEnum.UserRole)Enum.Parse(typeof(CustomEnum.UserRole), value.ToString());

            }
        }

用以下语句判断是否属于某种权限,并进行某种操作

 if (WebSession.UserRole == CustomEnum.UserRole.Visitor) //如果是普通游客 
                {
                    //跳转到登陆页面
                    filterContext.Result = new RedirectResult("/User/LogOn?ReturnUrl=" + filterContext.HttpContext.Request.Url);
                }
                else
                {
                    //跳转到权限提醒页面
                    filterContext.Result = new RedirectResult("/Home/Role?ReturnUrl=" + filterContext.HttpContext.Request.Url);
                }

posted @ 2011-09-30 16:04  张占岭  阅读(2324)  评论(0编辑  收藏  举报