I am trying to figure out how to prevent access to a controller's method if user is not logged in or is not an admin. I have a class with variables inside which keep track of the user and his state (logged in, admin, etc.).
I think this can be done by using a ValidationAttribute. I have not used this technique before so I am probably doing something wrong.
AccountController.CS
[AdminUserValidation]
public ActionResult Index()
{
var account1 = account.GetAccountsWithType();
return View(account1.ToList());
}
AdminUserValidation.CS
public class AdminUserValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (UserSession.Current.IsAdmin)
{
//Allow access to the controller's method
}
else
{
//Prevent access to the controller's method and show error page (bad request/forbidden)
}
base.OnActionExecuting(filterContext);
}
}