如何正确获取控制器类上标注的DisplayName属性值?
问题原因
你将DisplayNameAttribute标注在控制器类上,但原有代码是从Action方法的元数据MethodInfo中读取该特性,二者所属对象不匹配,因此无法拿到对应值,返回null。
修改方案
只需将读取特性的数据源从MethodInfo改为控制器类型ControllerType即可,修正后代码如下:
using System.Reflection; // 需提前引入该命名空间 public IList<ActionAndControllerName> AreaAndActionAndControllerNamesList() { var endpoints = endpointSources .SelectMany(es => es.Endpoints) .OfType<RouteEndpoint>(); var output = endpoints.Select( e => { var controller = e.Metadata .OfType<ControllerActionDescriptor>() .FirstOrDefault(); return new ActionAndControllerName // 替换原有匿名类为你定义的强类型 { Controller = controller.ControllerName, // 核心修改:从控制器类型读取特性 ControllerDisplayName = controller.ControllerType.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName, }; }) // 可选:去重,避免同一个控制器多个Action导致重复条目 .DistinctBy(x => x.Controller) .ToList(); return output; }
如果你不需要去重可直接删除
DistinctBy相关代码即可。
内容的提问来源于stack exchange,提问作者farshid azizi
相关产品推荐
相关产品推荐

