我设法获得了项目中所有控制器及其各自操作的列表。我现在正在尝试创建一个自定义属性,用于每个动作,我可以设置属性,例如动作描述例如。 "这会创建一个用户"。这似乎工作正常但现在问题是:我如何检索每个操作的自定义属性?
下面列出了所有控制器和操作。我只需要获取名为AccessControl的每个动作自定义属性
var controlleractionlist = asm.GetTypes()
.Where(type => typeof(System.Web.Mvc.Controller).IsAssignableFrom(type))
.SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
.Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
.Select(x => new { Controller = x.DeclaringType.Name, Action = x.Name, CustomAttr = x.DeclaringType.GetCustomAttributes(typeof(AccessControl), false).Cast<AccessControl>()})
.OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList();
典型控制器操作的示例
[HttpGet]
[AccessControl(Description="Creates a user")]
public ActionResult Index()
{
return View();
}
最后我的自定义属性类
public class AccessControl : AuthorizeAttribute
{
public string Description { get; set; }
}
谢谢
答案 0 :(得分:0)
使用此:
Expression<Action<YourController>> myAction = m => m.Index();
var method = ((MethodCallExpression)myAction.Body).Method;
var statusAttributes = method.GetCustomAttributes();
您可以从上面的statusAttributes集合中获取所有服装属性。
答案 1 :(得分:0)
var controlleractionlist = asm.GetTypes()
.Where(type => typeof(System.Web.Mvc.Controller).IsAssignableFrom(type))
.SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
.Where(m => m.GetCustomAttributes(typeof(AccessControl), true).Any() )
.Select(x => new { Controller = x.DeclaringType.Name, Action = x.Name, CustomAttr = x.GetCustomAttributes(typeof(AccessControl), false).Cast<AccessControl>() })
.OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList();