【问题标题】:how to get DisplayName Attribute Value from Controller type?如何从控制器类型中获取 DisplayName 属性值?
【发布时间】:2021-06-14 11:55:09
【问题描述】:

我在控制器顶部有一个 DisplayName 属性。 我的主要需求是给控制器设置一个昵称,当我拿到所有控制器后,除了原来的名字外,我还可以访问昵称。

几个控制器之一:

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

我的扩展方法:

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

为此,我在控制器顶部定义了一个 DisplayName,现在我必须为其命名。 当然,这是我想到的。如果您有其他想法,请告诉我,如果没有,请帮助我的想法。

【问题讨论】:

    标签: c# asp.net asp.net-core methods attributes


    【解决方案1】:

    是这样写的。

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

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 2023-03-30
      • 2015-03-11
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 2020-08-21
      相关资源
      最近更新 更多