You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改代码从Controller的[Display]特性中获取DisplayName?

从控制器的Display特性中获取显示名称

要实现从控制器类的[Display(Name = "...")]特性里提取对应的显示名称,你可以借助反射来读取类型上的特性信息。这里是修改后的实现方案,我会拆解关键步骤帮你理解:

基础实现:仅返回显示名称

下面的方法会遍历程序集中的所有控制器,提取它们的Display特性名称(如果存在),否则返回去掉Controller后缀的类名作为默认值:

using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Microsoft.AspNetCore.Mvc;

public IEnumerable<string> GetControllerDisplayNames(Assembly assembly)
{
    var controllerDisplayNames = assembly.GetExportedTypes()
        // 筛选出所有ControllerBase的派生类(即控制器)
        .Where(t => typeof(ControllerBase).IsAssignableFrom(t))
        .Select(t => 
        {
            // 获取当前控制器类型上的Display特性实例
            var displayAttribute = t.GetCustomAttribute<DisplayAttribute>();
            
            // 特性存在则返回Name值,否则返回去掉"Controller"后缀的类名
            return displayAttribute?.Name ?? t.Name.Replace("Controller", string.Empty);
        })
        .ToList();
    
    return controllerDisplayNames;
}

关键逻辑说明

  • 读取特性:使用Type.GetCustomAttribute<DisplayAttribute>()方法,它会查找当前类型上标记的Display特性,找到则返回特性实例,找不到返回null。
  • 默认值处理:用空合并运算符??做兜底:如果特性不存在,就把控制器类名的Controller后缀去掉(比如CategoryController变成Category),你也可以根据需求改成其他默认逻辑,比如直接返回完整类名。

进阶实现:同时保留控制器类型和显示名称

如果你需要同时获取控制器的类型信息和对应的显示名称,可以返回元组或者自定义类,示例如下:

public IEnumerable<(Type ControllerType, string DisplayName)> GetControllerWithDisplayNames(Assembly assembly)
{
    return assembly.GetExportedTypes()
        .Where(t => typeof(ControllerBase).IsAssignableFrom(t))
        .Select(t => 
        {
            var displayAttribute = t.GetCustomAttribute<DisplayAttribute>();
            var displayName = displayAttribute?.Name ?? t.Name.Replace("Controller", string.Empty);
            return (ControllerType: t, DisplayName: displayName);
        })
        .ToList();
}

这样调用后,你就能同时拿到控制器的类型对象和对应的显示名称,方便后续做更多处理。

内容的提问来源于stack exchange,提问作者kianoush

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:01:42