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)
你得到以下输出:

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)
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文档。
编辑您可能会找到有关此问题的更多信息。
我正在寻找一种方法来获得区域,控制器和动作,为此我设法改变你在这里发布的方法,所以如果有人想找到一个方法来获得 这里的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)
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)
如果它可以帮助任何人,我改进了@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)
(归功于这个答案)
并更新PropertyDescription为public List<string> PropertyDescription { get; set; }
| 归档时间: |
|
| 查看次数: |
45081 次 |
| 最近记录: |