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

Sta*_*855 9 c# asp.net asp.net-core-mvc asp.net-core

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

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

我的控制器:

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

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

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

有可能以ActionAttribute实用的方式阅读所有内容吗?

MaK*_*MKo 17

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

typeof(youClass).GetCustomAttributes<YourAttribute>();
// or
// if you need only one attribute
typeof(youClass).GetCustomAttribute<YourAttribute>();
Run Code Online (Sandbox Code Playgroud)

它会回来IEnumerable<YourAttribute>.

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

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

编辑:

对于CoreCLR,您需要再调用一个方法,因为API已经更改了一点:

typeof(youClass).GetTypeInfo().GetCustomAttributes<YourAttribute>();
Run Code Online (Sandbox Code Playgroud)

  • 'Type'不包含'GetCustomAttributes'的定义 (2认同)
  • 我刚编辑了答案.请看一下. (2认同)