【问题标题】:Getting Controller details in ASP.NET Core在 ASP.NET Core 中获取控制器详细信息
【发布时间】:2016-09-02 03:35:53
【问题描述】:

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

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

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 中找不到此类的等效项。我遇到了IActionDescriptorCollectionProvider,它似乎提供了有限的细节。

问题

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

非常感谢您的帮助

【问题讨论】:

  • 也许尝试注入 IActionDescriptorCollectionProvider 并使用它来检索所需的 ControllerActionDescriptor 实例,如 here 所述

标签: c# asp.net asp.net-mvc asp.net-core asp.net-core-1.0


【解决方案1】:

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

您可能不会将ActionDescriptor 转换为ControllerActionDescriptor。相关信息为here

我的目标是在 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;
    }

【讨论】:

    猜你喜欢
    • 2022-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    相关资源
    最近更新 更多