在C#中获取所有控制器和操作名称

sag*_*eer 55 c# asp.net-mvc asp.net-mvc-controller

是否可以以编程方式列出所有控制器的名称及其操作?

我想为每个控制器和操作实现数据库驱动的安全性.作为开发人员,我知道所有控制器和操作,并且可以将它们添加到数据库表中,但有没有办法自动添加它们?

AVH*_*AVH 83

以下将提取控制器,操作,属性和返回类型:

Assembly asm = Assembly.GetAssembly(typeof(MyWebDll.MvcApplication));

var controlleractionlist = asm.GetTypes()
        .Where(type=> typeof(System.Web.Mvc.Controller).IsAssignableFrom(type))
        .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
        .Where(m => !m.GetCustomAttributes(typeof( System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
        .Select(x => new {Controller = x.DeclaringType.Name, Action = x.Name, ReturnType = x.ReturnType.Name, Attributes = String.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute",""))) })
        .OrderBy(x=>x.Controller).ThenBy(x => x.Action).ToList();
Run Code Online (Sandbox Code Playgroud)

如果您在linqpad中运行此代码并调用

controlleractionlist.Dump();
Run Code Online (Sandbox Code Playgroud)

你得到以下输出:

在此输入图像描述

  • @LucianBumb - "MyWebDll"只是您的Web应用程序的主dll(或MvcApplication类所在的命名空间)的占位符.查看您的Global.asax.cs文件,您将看到类似于"public class MvcApplication:System.Web.HttpApplication"的内容.将示例中的"MyWebDll"部分替换为Web应用程序DLL或命名空间的名称(如果您不确定程序集名称,请检查项目属性窗口或bin文件夹).例如,如果我的项目生成一个名为"AmosCo.Enterprise.Website.dll"的DLL,那么我将使用"AmosCo.Enterprise.Website.MvcApplication" (4认同)
  • 要使此查询在LinqPad中运行,请按F4键打开“查询属性”>“浏览”>转到应用程序的bin / debug / MyApp.dll(或发行文件夹)并选择。也对同一文件夹中的“ System.Web.Mvc.dll”执行相同的操作。然后将“ MyWebDll”更改为“ MyApp”(您的应用dll的名称)。不要忘记添加转储语句。 (2认同)
  • 如果您遇到此异常“无法加载一种或多种请求的类型。检索 LoaderExceptions 属性以获取更多信息。使用“System.Net.Http”(或类似的 DLL),尝试下载 Linqpad 4。问题出在 .NET Framework 和 Standard 上。 (2认同)

dca*_*tro 72

您可以使用反射来查找当前程序集中的所有控制器,然后找到未使用该NonAction属性修饰的公共方法.

Assembly asm = Assembly.GetExecutingAssembly();

asm.GetTypes()
    .Where(type=> typeof(Controller).IsAssignableFrom(type)) //filter controllers
    .SelectMany(type => type.GetMethods())
    .Where(method => method.IsPublic && ! method.IsDefined(typeof(NonActionAttribute)));
Run Code Online (Sandbox Code Playgroud)

  • @ArsenMkrt不需要Action方法来返回ActionResult的衍生物.例如,MVC非常乐意执行一个在其签名中返回`string`的动作方法. (3认同)

Pie*_*ier 12

所有这些答案都依赖于反射,尽管它们有效,但它们试图模仿中间件的作用。

此外,您可以通过不同的方式添加控制器,并且在多个组件中运送控制器的情况并不罕见。在这种情况下,依赖反射需要太多的知识:例如,您必须知道要包含哪些程序集,并且当手动注册控制器时,您可能会选择特定的控制器实现,从而遗漏了一些合法的控制器通过反射拾取。

在ASP.NET Core中获取注册控制器(无论它们在哪里)的正确方法是需要此服务IActionDescriptorCollectionProvider

ActionDescriptors属性包含所有可用操作的列表。每个都ControllerActionDescriptor提供详细信息,包括名称、类型、路由、参数等。

var adcp = app.Services.GetRequiredService<IActionDescriptorCollectionProvider>();
var descriptors = adcp.ActionDescriptors
                      .Items
                      .OfType<ControllerActionDescriptor>();
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅MSDN文档。

编辑您可能会找到有关此问题的更多信息。


Luc*_*umb 8

我正在寻找一种方法来获得区域,控制器和动作,为此我设法改变你在这里发布的方法,所以如果有人想找到一个方法来获得 这里AREA是我的丑陋方法(我保存到一个xml):

 public static void GetMenuXml()
        {
       var projectName = Assembly.GetExecutingAssembly().FullName.Split(',')[0];

        Assembly asm = Assembly.GetAssembly(typeof(MvcApplication));

        var model = asm.GetTypes().
            SelectMany(t => t.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
            .Where(d => d.ReturnType.Name == "ActionResult").Select(n => new MyMenuModel()
            {
                Controller = n.DeclaringType?.Name.Replace("Controller", ""),
                Action = n.Name,
                ReturnType = n.ReturnType.Name,
                Attributes = string.Join(",", n.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))),
                Area = n.DeclaringType.Namespace.ToString().Replace(projectName + ".", "").Replace("Areas.", "").Replace(".Controllers", "").Replace("Controllers", "")
            });

        SaveData(model.ToList());
    }
Run Code Online (Sandbox Code Playgroud)

编辑:

//assuming that the namespace is ProjectName.Areas.Admin.Controllers

 Area=n.DeclaringType.Namespace.Split('.').Reverse().Skip(1).First()
Run Code Online (Sandbox Code Playgroud)


Moh*_*eli 5

var result = Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(type => typeof(ApiController).IsAssignableFrom(type))
            .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
            .Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
            .GroupBy(x => x.DeclaringType.Name)
            .Select(x => new { Controller = x.Key, Actions = x.Select(s => s.Name).ToList() })
            .ToList();
Run Code Online (Sandbox Code Playgroud)


Ale*_*exB 5

如果它可以帮助任何人,我改进了@AVH的答案以使用递归来获取更多信息。
我的目标是创建一个自动生成的 API 帮助页面:

 Assembly.GetAssembly(typeof(MyBaseApiController)).GetTypes()
        .Where(type => type.IsSubclassOf(typeof(MyBaseApiController)))
        .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
        .Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
        .Select(x => new ApiHelpEndpointViewModel
        {
            Endpoint = x.DeclaringType.Name.Replace("Controller", String.Empty),
            Controller = x.DeclaringType.Name,
            Action = x.Name,
            DisplayableName = x.GetCustomAttributes<DisplayAttribute>().FirstOrDefault()?.Name ?? x.Name,
            Description = x.GetCustomAttributes<DescriptionAttribute>().FirstOrDefault()?.Description ?? String.Empty,
            Properties = x.ReturnType.GenericTypeArguments.FirstOrDefault()?.GetProperties(),
            PropertyDescription = x.ReturnType.GenericTypeArguments.FirstOrDefault()?.GetProperties()
                                        .Select(q => q.CustomAttributes.SingleOrDefault(a => a.AttributeType.Name == "DescriptionAttribute")?.ConstructorArguments ?? new List<CustomAttributeTypedArgument>() )
                                        .ToList()
        })
        .OrderBy(x => x.Controller)
        .ThenBy(x => x.Action)
        .ToList()
        .ForEach(x => apiHelpViewModel.Endpoints.Add(x)); //See comment below
Run Code Online (Sandbox Code Playgroud)

(只需更改最后一个ForEach()子句,因为我的模型封装在另一个模型中)。
对应的ApiHelpViewModel是:

public class ApiHelpEndpointViewModel
{
    public string Endpoint { get; set; }
    public string Controller { get; set; }
    public string Action { get; set; }
    public string DisplayableName { get; set; }
    public string Description { get; set; }
    public string EndpointRoute => $"/api/{Endpoint}";
    public PropertyInfo[] Properties { get; set; }
    public List<IList<CustomAttributeTypedArgument>> PropertyDescription { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

当我的端点返回时IQueryable<CustomType>,最后一个属性 ( PropertyDescription) 包含许多与CustomType的属性相关的元数据。[Description]因此,您可以获得每个属性的名称、类型、描述(添加注释)等CustomType's

它比原来的问题更进一步,但如果它可以帮助某人......


更新

更进一步,如果您想添加一些[DataAnnotation]无法修改的字段(因为它们是由模板生成的),您可以创建一个MetadataAttributes类:

[MetadataType(typeof(MetadataAttributesMyClass))]
public partial class MyClass
{
}

public class MetadataAttributesMyClass
{
    [Description("My custom description")]
    public int Id {get; set;}

    //all your generated fields with [Description] or other data annotation
}
Run Code Online (Sandbox Code Playgroud)

小心MyClass 必须

  • 部分班级,
  • 与生成的名称空间相同MyClass

然后,更新检索元数据的代码:

Assembly.GetAssembly(typeof(MyBaseController)).GetTypes()
        .Where(type => type.IsSubclassOf(typeof(MyBaseController)))
        .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
        .Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
        .Select(x =>
        {
            var type = x.ReturnType.GenericTypeArguments.FirstOrDefault();
            var metadataType = type.GetCustomAttributes(typeof(MetadataTypeAttribute), true)
                .OfType<MetadataTypeAttribute>().FirstOrDefault();
            var metaData = (metadataType != null)
                ? ModelMetadataProviders.Current.GetMetadataForType(null, metadataType.MetadataClassType)
                : ModelMetadataProviders.Current.GetMetadataForType(null, type);

            return new ApiHelpEndpoint
            {
                Endpoint = x.DeclaringType.Name.Replace("Controller", String.Empty),
                Controller = x.DeclaringType.Name,
                Action = x.Name,
                DisplayableName = x.GetCustomAttributes<DisplayAttribute>().FirstOrDefault()?.Name ?? x.Name,
                Description = x.GetCustomAttributes<DescriptionAttribute>().FirstOrDefault()?.Description ?? String.Empty,
                Properties = x.ReturnType.GenericTypeArguments.FirstOrDefault()?.GetProperties(),
                PropertyDescription = metaData.Properties.Select(e =>
                {
                    var m = metaData.ModelType.GetProperty(e.PropertyName)
                        .GetCustomAttributes(typeof(DescriptionAttribute), true)
                        .FirstOrDefault();
                    return m != null ? ((DescriptionAttribute)m).Description : string.Empty;
                }).ToList()
            };
        })
        .OrderBy(x => x.Controller)
        .ThenBy(x => x.Action)
        .ToList()
        .ForEach(x => api2HelpViewModel.Endpoints.Add(x));
Run Code Online (Sandbox Code Playgroud)

(归功于这个答案

并更新PropertyDescriptionpublic List<string> PropertyDescription { get; set; }