获得在C#中的所有控制器和动作名称

问题描述:

是可以读取所有控制器和他们的行动务实的名字?

is it possible to read all the controllers and their actions name pragmatically?

我要实现为每个控制器和行动的数据库驱动的安全性。作为一个开发者,我知道所有的控制器和动作,可以在数据库表中添加他们,但对于有没有什么办法可以自动添加它们?

I want to implement database driven security for each controller and action. As a developer, i know all controllers and actions and can add them in database table but for is there any way to add them automatically?

您可以使用反射来查找当前集中的所有控制器,然后发现他们未装饰的无为属性。

You can use reflection to find all Controllers in the current assembly, and then find their public methods that are not decorated with the NonAction attribute.

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)));