【问题标题】:How to Find All Controller and Action如何找到所有控制器和动作
【发布时间】:2017-06-09 10:25:28
【问题描述】:

如何在 dotnet core 中找到所有具有其属性的控制器和动作? 在 .NET Framework 中,我使用了以下代码:

public static List<string> GetControllerNames()
{
    List<string> controllerNames = new List<string>();
    GetSubClasses<Controller>().ForEach(type => controllerNames.Add(type.Name.Replace("Controller", "")));
    return controllerNames;
}
public static List<string> ActionNames(string controllerName)
{
    var types =
        from a in AppDomain.CurrentDomain.GetAssemblies()
        from t in a.GetTypes()
        where typeof(IController).IsAssignableFrom(t) &&
            string.Equals(controllerName + "Controller", t.Name, StringComparison.OrdinalIgnoreCase)
    select t;

    var controllerType = types.FirstOrDefault();

    if (controllerType == null)
    {
        return Enumerable.Empty<string>().ToList();
    }
    return new ReflectedControllerDescriptor(controllerType)
       .GetCanonicalActions().Select(x => x.ActionName).ToList();
}

但它在 dotnet core 中不起作用。

【问题讨论】:

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


【解决方案1】:

IActionDescriptorCollectionProvider 注入到需要了解这些内容的组件中怎么样?它位于 Microsoft.AspNetCore.Mvc.Infrastructure 命名空间中。

此组件为您提供应用程序中可用的每一个操作。以下是它提供的数据示例:

作为奖励,您还可以评估所有过滤器、参数等。


附带说明一下,我想您可以使用反射来查找从ControllerBase 继承的类型。但是你知道你可以拥有不继承它的控制器吗?并且您可以编写覆盖这些规则的约定?出于这个原因,注入上述组件使其变得容易得多。您无需担心它会损坏。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多