【问题标题】:Changing DisplayName of controller .net core更改控制器 .net 核心的 DisplayName
【发布时间】:2021-07-14 11:16:46
【问题描述】:

我正在尝试使用以下方法更改我的 mvc .Net Core 应用程序中控制器或操作的 DisplayName: [DisplayName("MyName")] 在动作或控制器的顶部,但是当我通过此代码发现并显示它们时:

_actionDescriptorCollectionProvider
                         .ActionDescriptors
                         .Items
                         .OfType<ControllerActionDescriptor>()
                         .Select(a => new
                         {
                             a.DisplayName,
                             a.ControllerName,
                             a.ActionName,
                         
                         });

我仍然看到这样的默认命名: “MyProject.Controllers.LoginController.Index (MyProject)” 为什么是这样?为什么没变?

【问题讨论】:

    标签: asp.net-core model-view-controller controller


    【解决方案1】:

    似乎DisplayName 属性不尊重DisplayNameAttribute,即使查看了该属性使用的TypeNameHelper,我也找不到任何改变其行为的方法。

    你可以做的显而易见的事情就是使用反射

    //using System.Reflection;
    var result = _actionDescriptorCollectionProvider
        .ActionDescriptors
        .Items
        .OfType<ControllerActionDescriptor>()
        .Select(a => new
        {
            DisplayName = a.MethodInfo.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName ?? a.DisplayName,
            a.ControllerName,
            a.ActionName,
    
        }).ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      相关资源
      最近更新 更多