【问题标题】:get roles attribute of controller in OnActionExecuting in mvc在 mvc 中的 OnActionExecuting 中获取控制器的角色属性
【发布时间】:2015-06-14 11:51:30
【问题描述】:

我想在 OnActionExecuting 方法中读取控制器的过滤器属性。 为此我写了这段代码,但是这个空数组。

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 
        }
    }

这是我的控制器

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

            return View();
        }
    }

我想获取执行控制器的允许角色列表。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 actionfilterattribute


    【解决方案1】:

    您可以使用ActionDescriptorControllerDescriptorGetFilterAttributes方法:

        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);
            ...
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      • 1970-01-01
      • 2013-09-03
      • 2015-02-04
      • 2016-05-09
      • 2023-04-01
      相关资源
      最近更新 更多