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.
Here is what I am trying to do:
public List<string> ActionNames(string controllerName){
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With