mvc 3 session and authorizeAttribute

笑着哭i 提交于 2019-12-03 09:29:29

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();
    }
}

To keep this in line with ASP.NET security you should add the IsManager role to your membership/role system, then add that user to the role. No hacking required then and you can use the built in Authorize attribute.

Are you using the built in membership providers? If so this would be a snap.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!