How to get custom attributes for a controller in asp.net core rc2

纵饮孤独 提交于 2019-12-08 16:14:25

问题


I have created a custom attribute :

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

my controller :

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

my code : i use reflection to find all Controllers in the current assembly

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

is it possible to read all the ActionAttribute pragmatically?


回答1:


To get an attributes from the class you can do something the following:

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

it will return IEnumerable<YourAttribute>.

So, within your code it will be something like:

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

Edit:

In case with CoreCLR you need to call one more method, because the API has been changed a bit:

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



回答2:


The currently answer doesn't always work, but depends which entry point you use of your application. (It will break as example on unit tests).

To get all classes in the same assembly where your attribute is defined

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


来源:https://stackoverflow.com/questions/37465436/how-to-get-custom-attributes-for-a-controller-in-asp-net-core-rc2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!