get roles attribute of controller in OnActionExecuting in mvc

4.7k views Asked by At

I want to read the filter attributes of controller in OnActionExecuting method. for this I have written this code but this empty array.

public class BaseController : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var getActionName = filterContext.ActionDescriptor.ActionName;
            var getControllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var getUserName = User.Identity.Name;
            var getUserRoles = Roles.GetRolesForUser(getUserName);
            foreach (var filter in filterContext.ActionDescriptor.GetCustomAttributes(typeof(Roles), false))
            {
                var desiredValue = filter.ToString();
            }
           //some business logic here 
        }
    }

this is my controller

[Authorize(Roles = "Admin")]
    public class AdminController : BaseController
    {
         public ActionResult Index()
        {

            return View();
        }
    }

I want to get list of allowed roles for executing controller.

1

There are 1 answers

0
alisabzevari On BEST ANSWER

You can use GetFilterAttributes method of ActionDescriptor or ControllerDescriptor:

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var filters = new List<FilterAttribute>();
        filters.AddRange(filterContext.ActionDescriptor.GetFilterAttributes(false));
        filters.AddRange(filterContext.ActionDescriptor.ControllerDescriptor.GetFilterAttributes(false));
        var roles = filters.OfType<AuthorizeAttribute>().Select(f => f.Roles);
        ...
    }