Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 742
StackOverflow4855 Avatar asked May 26 '16 15:05

StackOverflow4855


People also ask

How can create custom attribute in core in asp net?

Declaring Custom AttributesWe can define an attribute by creating a class. This class should inherit from the Attribute class. Microsoft recommends appending the 'Attribute' suffix to the end of the class's name. After that, each property of our derived class will be a parameter of the desired data type.

How can you specify target for custom attribute?

Which of the following are correct ways to specify the targets for a custom attribute? A. By applying AttributeUsage to the custom attribute's class definition.

How do I override an authorized attribute in .NET Core?

We have code base ready, we need to implement the wrapper class to handle the API request. Right-click on the solution and add a new class. Enter the class name and click on Add. Next Inherite Attribute, IAuthorizationFilter to CustomAuthorization class which has overridden the OnAuthorization method.


1 Answers

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>();
like image 119
MaKCbIMKo Avatar answered Oct 27 '22 01:10

MaKCbIMKo