Mvc 3 session and authorizeAttribute

My site is open to everyone, but I have a controller with some method that only a manager with a user and password can enter. I save the bool IsManager in session .
I would like to use the authorize attribute to block someone IsManager == false .

+4
source share
2 answers

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 on a limited action (or controller):

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

To preserve this in accordance with ASP.NET security, you must add the IsManager role to your membership / role system and then add this user to the role. Then no hack is required, and you can use the built-in Authorize attribute.

Do you use built-in membership providers? If so, it will be easy.

+1
source

Source: https://habr.com/ru/post/1402704/


All Articles