如何找到所有控制器和动作

How to Find All Controller and Action(如何找到所有控制器和动作)

本文介绍了如何找到所有控制器和动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to find all controllers and actions with its attribute in dotnet core? In .NET Framework I used this code:

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 中不起作用.

but its not working in dotnet core.

推荐答案

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

How about injecting IActionDescriptorCollectionProvider to your component that needs to know these things? It's in the Microsoft.AspNetCore.Mvc.Infrastructure namespace.

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

This component gives you every single action available in the app. Here is an example of the data it provides:

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

As a bonus, you can also evaluate all of the filters, parameters etc.

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

As a side note, I suppose you could use reflection to find the types that inherit from ControllerBase. But did you know you can have controllers that don't inherit from it? And that you can write conventions that override those rules? For this reason, injecting the above component makes it a lot easier. You don't need to worry about it breaking.

这篇关于如何找到所有控制器和动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何找到所有控制器和动作

基础教程推荐