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

I 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 the 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 ActionAttribute ?

+7
c # asp.net-core asp.net-core-mvc
source share
2 answers

To get attributes from a class, you can do something like the following:

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

it will return an IEnumerable<YourAttribute> .

So in your code this 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 the case of CoreCLR, you need to call another method because the API has been slightly modified:

 typeof(youClass).GetTypeInfo().GetCustomAttributes<YourAttribute>(); 
+14
source share

Currently, the answer does not always work, but it depends on which entry point you use in your application. (It will be broken as an example into 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); } } 
0
source share

All Articles