2016-05-26 15 views
7

Ho creato un attributo personalizzato:Come ottenere personalizzato per un controller a nucleo asp.net RC2

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

mio controller:

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

mio codice: io uso di riflessione per trovare tutti Controller nell'assieme corrente

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

è possibile leggere tutte le ActionAttribute pragmaticamente?

risposta

14

per ottenere un attributi dalla classe si può fare qualcosa quanto segue:

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

tornerà IEnumerable<YourAttribute>.

Quindi, all'interno del codice che sarà qualcosa di simile a:

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

Edit:

Nel caso in cui con CoreCLR è necessario chiamare un metodo di più, perché l'API è stato cambiato un po ' :

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

'Tipo' non contiene una definizione per '' GetCustomAttributes – StackOverflow4855

+2

Ho appena modificato la risposta. Per favore dai un'occhiata. – MaKCbIMKo

+0

'Assembly.GetEntryAssembly()' otterrà l'assembly utilizzato come voce. Quindi, il comportamento sarà diverso nell'esempio dei test dell'unità. –

0

La risposta corrente non funziona sempre, ma dipende dal punto di ingresso che si utilizza dell'applicazione. (Si romperà come un esempio sui test unitari).

Per ottenere tutte le classi nello stesso assembly in cui il vostro attributo è definito

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