mvc 3 session and authorizeAttribute

前端 未结 2 1896
时光取名叫无心
时光取名叫无心 2021-02-10 13:46

My site is open to all but i have a controller with some method that only the manager with the user and password can enter. I\'m saving the bool IsManager in a

2条回答
  •  粉色の甜心
    2021-02-10 14:27

    First define an ActionFilter:

    public class TheFilter: ActionFilterAttribute
    {
       public override void OnActionExecuting(ActionExecutingContext filterContext)
       {
            var session = filterContext.HttpContext.Session;
            if ((bool?)session["IsManager"] == true)
                return;
    
            //Redirect him to somewhere.
            var redirectTarget = new RouteValueDictionary
                 {{"action", "{ActionName}"}, {"controller", "{ControllerName}"}};
            filterContext.Result = new RedirectToRouteResult(redirectTarget);
       }
    }
    

    Then use it above the restricted Action(or controller):

    //[TheFilter]
    public class ManagersController : Controller
    {
        [TheFilter]
        public ActionResult Foo()
        {
            ...
            return View();
        }
    }
    

提交回复
热议问题