how to get DisplayName Attribute Value from Controller type?

Viewed 58

I have an DisplayName Attribute on top of the controller. My main need is to set a nickname for the controllers of When I get all the controllers, I can access the nickname in addition to the original name.

One of several controllers :

 [DisplayName("نقش ها")]
public class RoleController : BaseController
{
    
  
}

My Extension Method :

 var controllerActionList = assembly.GetTypes()
            .Where(type => typeof(Controller).IsAssignableFrom(type))
            .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
            .Select(x => new
            {
                Area = x.DeclaringType?.CustomAttributes.Where(c => c.AttributeType == typeof(AreaAttribute)),
                Controller = x.DeclaringType,
                Action = x
            }).ToList();

        foreach (var item in controllerActionList)
        {
            var controleerDisplayName = item.Controller.DisplayName();
        }

To do this, I defined a DisplayName at the top of the controller and now I have to name it. Of course, this is what came to my mind. If you have another idea, tell me and if not, help my idea.

1 Answers

This is how it is written.

var controllerActionList = assembly.GetTypes()
        .Where(type => typeof(Controller).IsAssignableFrom(type))
        .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
        .Select(x => new
        {
            Area = x.DeclaringType?.CustomAttributes.Where(c => c.AttributeType == typeof(AreaAttribute)),
            Controller = x.DeclaringType,
            Action = x
        }).ToList();

    foreach (var item in controllerActionList)
    {
        var controleerDisplayName = item.Controller.GetTypeInfo().GetCustomAttribute<DisplayNameAttribute>()?.DisplayName;
    }
Related