如何在运行asp core 3.1时获取所有动作,控制器和区域名称

问题描述 投票:0回答:2

我有一个asp.net core 3.1应用程序,我想在我的应用程序运行时获取所有的控制器,动作和区域名称,就像在mvc中获取带有反射的动作名称一样。有什么办法吗?

asp.net-mvc asp.net-mvc-4 asp.net-core reflection .net-core
2个回答
0
投票

尝试一下:

ControllerFeature controllerFeature = new ControllerFeature();
this.ApplicationPartManager.PopulateFeature(controllerFeature);
IEnumerable<TypeInfo> typeInfos = controllerFeature.Controllers;

ApplicationPartManager必须对您的类使用DI。


0
投票

尝试一下:

1.Model:

public class ControllerActions
{
    public string Controller { get; set; }
    public string Action { get; set; }
    public string Area { get; set; }
}

2。显示控制器,动作和区域名称:

[HttpGet]
public List<ControllerActions> Index()
{
    Assembly asm = Assembly.GetExecutingAssembly();
    var controlleractionlist = asm.GetTypes()
            .Where(type => typeof(Controller).IsAssignableFrom(type))
            .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
            .Select(x => new
            {
                Controller = x.DeclaringType.Name,
                Action = x.Name,
                Area = x.DeclaringType.CustomAttributes.Where(c => c.AttributeType == typeof(AreaAttribute))

            }).ToList();
    var list = new List<ControllerActions>();
    foreach (var item in controlleractionlist)
    {
        if (item.Area.Count() != 0)
        {
            list.Add(new ControllerActions()
            {
                Controller = item.Controller,
                Action = item.Action,
                Area = item.Area.Select(v => v.ConstructorArguments[0].Value.ToString()).FirstOrDefault()
            });
        }
        else
        {
            list.Add(new ControllerActions()
            {
                Controller = item.Controller,
                Action = item.Action,
                Area = null,
            });
        }
    }
    return list;
}
© www.soinside.com 2019 - 2024. All rights reserved.