How can I get the list of all actions of Controller? I search but cannot find example/answer. I see some example recommended using reflection but I don\'t know how.
<You haven't told us why you need this but one possibility is to use reflection:
public List<string> ActionNames(string controllerName)
{
var types =
from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
where typeof(IController).IsAssignableFrom(t) &&
string.Equals(controllerName + "Controller", t.Name, StringComparison.OrdinalIgnoreCase)
select t;
var controllerType = types.FirstOrDefault();
if (controllerType == null)
{
return Enumerable.Empty<string>().ToList();
}
return new ReflectedControllerDescriptor(controllerType)
.GetCanonicalActions().Select(x => x.ActionName)
.ToList();
}
Obviously as we know reflection is not very fast so if you intend to call this method often you might consider improving it by caching the list of controllers to avoid fetching it everytime and even memoizing the method for given input parameters.
A slight tweak to Darin's answer. I needed this change to get this to work with code lense as it runs under a different assembly.
public static List<string> GetAllActionNames(string controllerName)
{
var controllerType = Assembly.Load("YourAssemblyNameHere")
.GetTypes()
.FirstOrDefault(x => typeof(IController).IsAssignableFrom(x)
&& x.Name.Equals(controllerName + "Controller", StringComparison.OrdinalIgnoreCase));
if (controllerType == null)
{
return Enumerable.Empty<string>().ToList();
}
return new ReflectedControllerDescriptor(controllerType)
.GetCanonicalActions().Select(x => x.ActionName)
.ToList();
}