Asp.NET MVC 中登录验证(BaseController自定义控制器)

可以声明一个自定义控制器BaseController继承Controller重写Controller中的OnActionExecuting虚方法,然后其他控制器继承BaseController就可以,避免了给每个控制器打个过滤标签去验证

public class BaseController : Controller
    {
        
        public UserInfo LoginUser { get; set; }
        /// <summary>
        /// 执行控制器中的方法之前先执行该方法。
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            //if (Session["userInfo"] == null)
            bool isSucess = false;
            if(Request.Cookies["sessionId"]!=null)
            {
                string sessionId = Request.Cookies["sessionId"].Value;
                //根据该值查Memcache.
                object obj=Common.MemcacheHelper.Get(sessionId);
                if(obj!=null)
                {
                    UserInfo userInfo = Common.SerializeHelper.DeserializeToObject<UserInfo>(obj.ToString());
                   LoginUser = userInfo;
                   isSucess = true;
                   Common.MemcacheHelper.Set(sessionId, obj, DateTime.Now.AddMinutes(20));//模拟出滑动过期时间.
                    //留一个后门,测试方便。发布的时候一定要删除该代码。
                   if (LoginUser.UName == "itcast")
                   {
                       return;
                   }
                    //完成权限校验。
                    //获取用户请求的URL地址.
                   string url = Request.Url.AbsolutePath.ToLower();
                    //获取请求的方式.
                   string httpMehotd = Request.HttpMethod;
                    //根据获取的URL地址与请求的方式查询权限表。
                   IApplicationContext ctx = ContextRegistry.GetContext();
                   IBLL.IActionInfoService ActionInfoService = (IBLL.IActionInfoService)ctx.GetObject("ActionInfoService");
                  var actionInfo= ActionInfoService.LoadEntities(a=>a.Url==url&&a.HttpMethod==httpMehotd).FirstOrDefault();
                  if (actionInfo != null)
                  {
                      filterContext.Result = Redirect("/Error.html");
                      return;
                  }

                    //判断用户是否具有所访问的地址对应的权限
                   IUserInfoService UserInfoService = (IUserInfoService)ctx.GetObject("UserInfoService");
                   var loginUserInfo = UserInfoService.LoadEntities(u=>u.ID==LoginUser.ID).FirstOrDefault();
                    //1:可以先按照用户权限这条线进行过滤。
                   var isExt =(from a in loginUserInfo.R_UserInfo_ActionInfo
                               where a.ActionInfoID == actionInfo.ID
                               select a).FirstOrDefault();
                   if (isExt != null)
                   {
                       if (isExt.IsPass)
                       {
                           return;
                       }
                       else
                       {
                           filterContext.Result = Redirect("/Error.html");
                           return;
                       }

                   }
                    //2:按照用户角色权限这条线进行过滤。
                   var loginUserRole = loginUserInfo.RoleInfo;
                   var count = (from r in loginUserRole
                               from a in r.ActionInfo
                               where a.ID == actionInfo.ID
                               select a).Count();
                   if (count < 1)
                   {
                       filterContext.Result = Redirect("/Error.html");
                       return;
                   }
                    

                }
               
               

              //  filterContext.HttpContext.Response.Redirect("/Login/Index");
               
            }
            if (!isSucess)
            {
                filterContext.Result = Redirect("/Login/Index");//注意.
            }
        }
    }
其他继承BaseController
 //统一检查权限问题
    public class ActionInfoController : BaseController
    {
        //
        // GET: /ActionInfo/
        IBLL.IActionInfoService ActionInfoService { get; set; }
        public ActionResult Index()
        {
            return View();
        }
        #region 获取权限信息
        public ActionResult GetActionInfoList()
        {

            int pageIndex = Request["page"] != null ? int.Parse(Request["page"]) : 1;
            int pageSize = Request["rows"] != null ? int.Parse(Request["rows"]) : 5;
            int totalCount;
            short delFlag = (short)DeleteEnumType.Normarl;
            var actionInfoList = ActionInfoService.LoadPageEntities<int>(pageIndex, pageSize, out totalCount, r => r.DelFlag == delFlag, r => r.ID, true);
            var temp = from r in actionInfoList
                       select new { ID = r.ID, ActionInfoName = r.ActionInfoName, Sort = r.Sort, SubTime = r.SubTime, Remark = r.Remark, Url = r.Url, ActionTypeEnum = r.ActionTypeEnum, HttpMethod = r.HttpMethod };
            return Json(new { rows = temp, total = totalCount }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 获取上传的文件.
        public ActionResult GetFileUp()
        {
            HttpPostedFileBase file=Request.Files["fileUp"];
            string fileName = Path.GetFileName(file.FileName);
            string fileExt = Path.GetExtension(fileName);
            if (fileExt == ".jpg")
            {
                string dir = "/ImageIcon/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
                Directory.CreateDirectory(Path.GetDirectoryName(Request.MapPath(dir)));
                string newfileName = Guid.NewGuid().ToString();
                string fullDir = dir + newfileName + fileExt;
                file.SaveAs(Request.MapPath(fullDir));
                //自己加上图片的缩略图
                return Content("ok:" + fullDir);
            }
            else
            {
                return Content("no:文件类型错误!!");
            }
        }
        
        #endregion

        #region 完成权限添加
        public ActionResult AddActionInfo(ActionInfo actionInfo)
        {
            actionInfo.DelFlag = 0;
            actionInfo.ModifiedOn = DateTime.Now.ToString();
            actionInfo.SubTime = DateTime.Now;
            actionInfo.Url = actionInfo.Url.ToLower();
            ActionInfoService.AddEntity(actionInfo);
            return Content("ok");
        }
        #endregion

    }


猜你喜欢

转载自blog.csdn.net/weixin_40184249/article/details/80219404