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:
[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[DisplayName("Test Name")]
public class RolesController : ControllerBase
{
...
}
my method:
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
{
Controller = controller.ControllerName,
ControllerDisplayName = controller.MethodInfo.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName,
};
}
But returns a null(ControllerDisplayName ). What needs to change?
Not sure what is your endpointSources
, but here is a working demo to get the controller name and Display Name:
Assembly asm = Assembly.GetExecutingAssembly();
var controllerlist = asm.GetTypes()
.Where(type => typeof(ControllerBase).IsAssignableFrom(type))
.Select(type => type.GetTypeInfo())
.Select(x => new
{
Controller = x.Name,
ControllerDisplayName = x.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName
}).ToList();
Result:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.