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 session
.
I would like to use the authorize attribute to block whom ever IsManager == false
.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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();
}
}
回答2:
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.