Getting All Controllers and Actions names in C#

前端 未结 9 1669
耶瑟儿~
耶瑟儿~ 2020-11-27 10:56

Is it possible to list the names of all controllers and their actions programmatically?

I want to implement database driven security for each controller and action.

9条回答
  •  余生分开走
    2020-11-27 11:48

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

提交回复
热议问题