Getting All Controllers and Actions names in C#

前端 未结 9 1676
耶瑟儿~
耶瑟儿~ 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:40

    I was looking for a way to get Area, Controller and Action and for this I manage to change a little the methods you post here, so if anyone is looking for a way to get the AREA here is my ugly method (which I save to an 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());
        }
    

    Edit:

    //assuming that the namespace is ProjectName.Areas.Admin.Controllers
    
     Area=n.DeclaringType.Namespace.Split('.').Reverse().Skip(1).First()
    

提交回复
热议问题