To prevent unauthorized users from accessing specific controllers or actions based on their permissions MVC, you should follow the below steps:
*Steps in details
PreventDirectAccessAttribute
ActionFilterAttribute
Within your custom filter, override the "OnActionExecuting" method. This method will be called before an action method in your controller is executed.
OnActionExecuting
public class PreventDirectAccessAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); } }
Retrieve the current controller and action from the incoming HTTP request using the following code:
var controllerName = filterContext.RequestContext.RouteData.Values["controller"] as string; var action = filterContext.RequestContext.RouteData.Values["action"] as string;
Determine the user's permissions and apply your access control logic. For example:
if (userPermission > 0 && userPermission==(int)Permission.CreateRequest && !((controllerName.Equals(Resources.Labels.ControllerApplication)) && action.Equals(Resources.Labels.ActionCreateApplication))) { // Access is allowed } else { // Access is denied }
Add the "PreventDirectAccessAttribute" above the controller name or action methods where you want to enforce this access control. For example:
[PreventDirectAccessAttribute] public class BaseController : Controller { }
1.1k questions
679 answers
459 comments
193k users
Related Activities
Categories
Most popular tags