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.
这篇关于如何找到所有控制器和动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何找到所有控制器和动作
基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01