在 ASP.NET 核心中获取控制器详细信息

Getting Controller details in ASP.NET Core

在ASP.NET4.x中,有一个ReflectedControllerDescriptorclass驻留在System.Web.Mvc中。 class 提供控制器的描述符。

在我以前的申请中,我曾经这样做过:

var controllerDescriptor = new ReflectedControllerDescriptor(controllerType);

var actions = (from a in controllerDescriptor.GetCanonicalActions()
              let authorize = (AuthorizeAttribute)a.GetCustomAttributes(typeof(AuthorizeAttribute), false).SingleOrDefault()
              select new ControllerNavigationItem
                 {
                    Action = a.ActionName,
                    Controller = a.ControllerDescriptor.ControllerName,
                    Text =a.ActionName.SeperateWords(),
                    Area = GetArea(typeNamespace),
                    Roles = authorize?.Roles.Split(',')
                 }).ToList();

return actions;

问题是我在 ASP.NET Core 中找不到这个 class 的任何等效项。我遇到了 IActionDescriptorCollectionProvider,它似乎提供了有限的细节。

问题

我的目标是在 ASP.NET Core 中编写等效代码。我该如何实现?

非常感谢您的帮助

I came across IActionDescriptorCollectionProvider which seems to provide limited details.

可能您没有将 ActionDescriptor 转换为 ControllerActionDescriptor。相关信息是here

My goal is to write an equivalent code in ASP.NET Core. How do I achieve that?

这是我在 ConfigureServices 方法中的尝试:

    var provider = services.BuildServiceProvider().GetRequiredService<IActionDescriptorCollectionProvider>();
    var ctrlActions = provider.ActionDescriptors.Items
            .Where(x => (x as ControllerActionDescriptor)
            .ControllerTypeInfo.AsType() == typeof(Home222Controller))
            .ToList();
    foreach (var action in ctrlActions)
    {
         var descriptor = action as ControllerActionDescriptor;
         var controllerName = descriptor.ControllerName;
         var actionName = descriptor.ActionName;
         var areaName = descriptor.ControllerTypeInfo
                .GetCustomAttribute<AreaAttribute>().RouteValue;
    }