Asp.NET MVCでのログイン検証(BaseControllerカスタムコントローラ)


カスタムコントローラBaseController継承Controllerを宣言してControllerのOnActionExecution虚メソッドを書き換え、他のコントローラがBaseControllerを継承すれば、各コントローラにフィルタラベルを付けて検証することを避けることができます.
public class BaseController : Controller
    {
        
        public UserInfo LoginUser { get; set; }
        /// 
        ///                  。
        /// 
        /// 
        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(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(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

    }