我在单元测试中使用了一些代码来验证某些操作是否用属性修饰。它使用具有一些可枚举扩展方法优点的反射。我想你可以适应这个。请注意,如果您只关心它是否存在,您可以在枚举上使用 Count() 而不是获取实际属性。这种方式允许您在使用属性属性来自定义行为方面具有一定的灵活性。使用继承树将允许您装饰整个控制器。
var methods= controller.GetType()
.GetMethods( BindingFlags.Public | BindingFlags.Instance )
foreach (var info in methods)
{
if (info.ReturnType == typeof(ActionResult))
{
var attribute = info.GetCustomAttributes( typeof( SiteMapAttribute ), true )
.Cast<SiteMapAttribute>()
.FirstOrDefault();
if (attribute != null && !attribute.Exclude.Contains( info.Name ))
{
...
}
}
}