Skip to content

Instantly share code, notes, and snippets.

@hitswa
Created December 2, 2024 06:47
Show Gist options
  • Save hitswa/b18a974f34bddc9d75294c626dc7e4a6 to your computer and use it in GitHub Desktop.
Save hitswa/b18a974f34bddc9d75294c626dc7e4a6 to your computer and use it in GitHub Desktop.
Get the list of all Controllers, Methods, Viewes of your .NET project
// Modal
public class ControllerActions
{
public string Controller { get; set; }
public string Action { get; set; }
public string Attributes { get; set; }
public string ReturnType { get; set; }
public string HttpMethods { get; set; }
public string ReturnsView { get; set; }
public string ViewPath { get; set; }
}
// API which will return result
// Replace <NAMESPACE> with your project namespace
public ActionResult GetAllControllerActions()
{
var asm = Assembly.GetAssembly(typeof(<NAMESPACE>.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", ""))),
HttpMethods = String.Join(",", x.GetCustomAttributes()
.OfType<ActionMethodSelectorAttribute>()
.Select(attr =>
{
if (attr is HttpGetAttribute) return "GET";
if (attr is HttpPostAttribute) return "POST";
if (attr is HttpPutAttribute) return "PUT";
if (attr is HttpDeleteAttribute) return "DELETE";
return "UNKNOWN";
})),
ReturnsView = typeof(ViewResult).IsAssignableFrom(x.ReturnType) || typeof(ActionResult).IsAssignableFrom(x.ReturnType),
ViewPath = $"~/Views/{x.DeclaringType.Name.Replace("Controller", "")}/{x.Name}.cshtml"
})
.OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList();
var list = new List<ControllerActions>();
foreach (var item in controlleractionlist)
{
list.Add(new ControllerActions()
{
Controller = item.Controller,
Action = item.Action,
Attributes = item.Attributes,
ReturnType = item.ReturnType,
HttpMethods = string.IsNullOrWhiteSpace(item.HttpMethods) ? "GET" : item.HttpMethods,
ReturnsView = item.ReturnsView ? "Yes" : "No",
ViewPath = item.ReturnsView ? item.ViewPath : "N/A"
});
}
return Json(list, JsonRequestBehavior.AllowGet);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment