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

Shi*_*nga 4 c# asp.net asp.net-mvc asp.net-core asp.net-core-1.0

在 ASP.NET 4.x 中,有一个ReflectedControllerDescriptor类驻留在System.Web.Mvc. 此类提供控制器的描述符。

在我以前的应用程序中,我曾经这样做过:

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;
Run Code Online (Sandbox Code Playgroud)

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

问题

我的目标是在 ASP.NET Core 中编写等效的代码。我如何做到这一点?

非常感谢您的帮助

ade*_*lin 7

我遇到了 IActionDescriptorCollectionProvider,它似乎提供了有限的细节。

可能你没有投射ActionDescriptorControllerActionDescriptor. 相关信息在这里

我的目标是在 ASP.NET Core 中编写等效的代码。我如何做到这一点?

这是我在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;
    }
Run Code Online (Sandbox Code Playgroud)