【问题标题】:How to get custom attributes for a controller in asp.net core rc2如何在 asp.net core rc2 中获取控制器的自定义属性
【发布时间】:2016-05-26 15:41:35
【问题描述】:

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

[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?

【问题讨论】:

    标签: c# asp.net asp.net-core asp.net-core-mvc


    【解决方案1】:

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

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

    它将返回IEnumerable&lt;YourAttribute&gt;。

    因此,在您的代码中,它将类似于:

    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>();
    

    【讨论】:

    • 'Type' 不包含 'GetCustomAttributes' 的定义
    • Assembly.GetEntryAssembly() 将获取用作条目的程序集。因此,在您的单元测试中,行为会有所不同。
    【解决方案2】:

    当前的答案并不总是有效,但取决于您使用应用程序的哪个入口点。 (它将作为单元测试的示例中断)。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 2016-09-23
      • 1970-01-01
      • 2011-04-03
      • 2019-11-04
      • 2011-07-31
      • 1970-01-01
      相关资源
      最近更新 更多