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

时间:2016-09-24 00:30:00

标签: c# asp.net-mvc asp.net-mvc-5

我已经看过几个类似的问题(但没有看到ActionName属性),答案(like this one)使用了Reflection。但是,它没有处理的是动作方法是否应用了Dim Response As Variant Response = MsgBox("Are you sure you want to delete this worksheet?", vbYesNo + vbExclamation, "Confirm Action") If Response = vbNo Then GoTo exit sub End If 'Save workbook prior to deletion as a precaution ThisWorkbook.Save ActiveSheet.Delete 。所以,如果我们有像

这样的东西
[ActionName]

在使用链接解决方案中显示的类似代码时,我不会将方法名称视为[ActionName('Profile')] public virtual ActionResult AccountProfile(...) ,而是Profile。对于我们的用例,这没有用。

我们目前正在使用MVC5。

1 个答案:

答案 0 :(得分:1)

试试这个:

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

    }