如何在asp.net core rc2中获取控制器的自定义属性

11

我已创建一个自定义属性:

[AttributeUsage(AttributeTargets.Method| AttributeTargets.Class)]
public class ActionAttribute : ActionFilterAttribute
{
    public int Id { get; set; }
    public string Work { get; set; }
}

我的控制器:

[Area("Administrator")]
[Action(Id = 100, Work = "Test")]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

我的代码:我使用反射在当前程序集中查找所有的控制器。

 Assembly.GetEntryAssembly()
         .GetTypes()
         .AsEnumerable()
         .Where(type => typeof(Controller).IsAssignableFrom(type))
         .ToList()
         .ForEach(d =>
         {
             // how to get ActionAttribute ?
         });

是否有可能以编程方式读取所有的ActionAttribute

2个回答

19

要从类中获取属性,可以执行以下操作:

typeof(youClass).GetCustomAttributes<YourAttribute>();
// or
// if you need only one attribute
typeof(youClass).GetCustomAttribute<YourAttribute>();

它将返回 IEnumerable<YourAttribute>

所以,在你的代码中,它应该是这样的:

Assembly.GetEntryAssembly()
        .GetTypes()
        .AsEnumerable()
        .Where(type => typeof(Controller).IsAssignableFrom(type))
        .ToList()
        .ForEach(d =>
        {
            var yourAttributes = d.GetCustomAttributes<YourAttribute>();
            // do the stuff
        });

编辑:

如果使用CoreCLR,你需要调用一个额外的方法,因为API已经有了一些变化:

typeof(youClass).GetTypeInfo().GetCustomAttributes<YourAttribute>();

2
“Type” 不包含 “GetCustomAttributes” 的定义。 - StackOverflow4855
Assembly.GetEntryAssembly()会获取用作入口的程序集。因此,在例如单元测试中,其行为将不同。 - Sander Visser

0

目前的答案并不总是适用,而是取决于您的应用程序使用哪个入口点。(例如,在单元测试中会出现错误)。

要获取定义属性的同一程序集中的所有类

var assembly = typeof(MyCustomAttribute).GetTypeInfo().Assembly;
foreach (var type in assembly.GetTypes())
{
  var attribute = type.GetTypeInfo().GetCustomAttribute<MyCustomAttribute>();
  if (attribute != null)
  {
      _definedPackets.Add(attribute.MarshallIdentifier, type);
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接