在运行时确定控制器上可用的操作(处理ActionName属性)

本文关键字:操作 处理 ActionName 属性 运行时 控制器 | 更新日期: 2023-09-27 18:08:38

我见过几个类似的问题(但没有wrt到ActionName属性)和答案(像这个)使用反射。然而,它不处理的是如果动作方法有一个应用于它的[ActionName]。所以如果我们有像

这样的东西
[ActionName('Profile')]
public virtual ActionResult AccountProfile(...)

当使用链接解决方案中所示的类似代码时,我不会看到方法名称为Profile,而是AccountProfile。对于我们的用例,这是不好的。

我们目前使用的是MVC5.

在运行时确定控制器上可用的操作(处理ActionName属性)

试试这个:

  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());
    }