1

I've seen several similar questions (but none wrt to the ActionName attribute) and the answers (like this one) use Reflection. However, what it doesn't handle is if the action method has an [ActionName] applied to it. So if we have something like

[ActionName('Profile')]
public virtual ActionResult AccountProfile(...)

I won't see the method name as Profile but rather AccountProfile when using similar code as shown in the linked solution. For our use case, that's no good.

We're currently using MVC5.

Community
  • 1
  • 1
emgee
  • 510
  • 3
  • 18

1 Answers1

1

Try this:

  IList<string> actionNames=new List<string>();
    Assembly asm = Assembly.GetExecutingAssembly();

    var methodInfos = asm.GetTypes()
        .Where(type => typeof(Controller).IsAssignableFrom(type)) //filter controllers
        .SelectMany(type => type.GetMethods())
        .Where(method => method.IsPublic &&method.CustomAttributes.Any(a=>a.AttributeType==typeof(ActionNameAttribute)));
    foreach (var methodInfo in methodInfos)
    {
        var actionAttribute =
            methodInfo.CustomAttributes.First(a => a.AttributeType == typeof(ActionNameAttribute));
        var actionName = actionAttribute.ConstructorArguments.First().Value;
        actionNames.Add(actionName.ToString());

    }
Tarek Abo ELkheir
  • 1,311
  • 10
  • 13