如何查找所有控制器和动作 [英] How to Find All Controller and Action

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

问题描述

如何在dotnet核心中找到具有其属性的所有控制器和动作? 在.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核心中不起作用.

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆