c# - 如何找到所有 Controller 和 Action

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

如何在 dotnet core 中找到所有具有其属性的 Controller 和 Action ? 在 .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 核心。

最佳答案

如何将 IActionDescriptorCollectionProvider 注入(inject)到需要知道这些事情的组件中?它位于 Microsoft.AspNetCore.Mvc.Infrastructure 命名空间中。

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

Action descriptor collection provider data sample

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


作为旁注,我想您可以使用反射来查找从 ControllerBase 继承的类型。但是你知道你可以拥有不从它继承的 Controller 吗?并且您可以编写覆盖这些规则的约定?因此,注入(inject)上述组件使其变得容易得多。您无需担心它会损坏。

关于c# - 如何找到所有 Controller 和 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44455384/

相关文章:

c# - Unity 着色器/C# - 如何更改效果颜色?

c# - 在单元测试中获取命令行参数

asp.net-core - EF Core 间歇性错误 : The connection does not support MultipleActiveResultSets

asp.net - 为什么 ASP.NET Core 将波斯语(或阿拉伯语)文本转换为 View 中的字符引用 (&#xhhhh;)

.net - 我可以使用 EF Code First 和 .net core 生成迁移脚本吗

c# - 绘制文本时 XNA 怪异的 3D 绘制

c# - 查询 refs 时如何排除存储?

c# - ReturnUrl 在使用 ASP.NET Core 6 MVC 的 POST 上始终为 null

c# - ASP.NET Core 同步和异步 Controller 操作之间没有太大区别

c# - ASP.NET Core 3.1 - WebApplicationFactory - WebApplicationFactoryContentRootAttribute 的正确用法是什么?