首页 > 代码库 > asp.net mvc 简单实现权限控制

asp.net mvc 简单实现权限控制

    public class HttpAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool _pass = false;

            if (httpContext.Session["UserName"] != null) {
                _pass = true;
            }

            return _pass;
        }

        /// <summary>
        /// 登录界面
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectResult("~/");
        }
    }

 加session

        [ValidateAntiForgeryToken()]
        [HttpPost]
        [AllowAnonymous]
        public ActionResult Index(ViewUser viewUser) {
            if (ModelState.IsValid) {
                var user = _user.Find(a => a.UserName == viewUser.UserName);
                if (user == null)
                {
                    ModelState.AddModelError("UserName", "用户名不存在");
                }
                else if (viewUser.Password != user.Password)
                {
                    ModelState.AddModelError("Password", "密码不正确");
                }
                else {
                    Session.Add("UserName", viewUser.UserName);
                    Session.Add("Password", viewUser.Password);
                    //ViewBag.LoginStatus = true;
                    //ViewBag.UserName = viewUser.UserName;
                    return RedirectToAction( "Index","Welcome");
                }
            
            }
            return View(viewUser);
        }

 

asp.net mvc 简单实现权限控制