2016-09-24 22 views
1

我已經看到了幾個類似的問題(但沒有用到ActionName屬性)和答案(like this one)使用了反射。但是,如果操作方法應用了[ActionName],則無法處理。使用類似的代碼,所以如果我們有像確定在控制器上的運行時可用操作(處理ActionName屬性)

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

我不會看到方法名Profile而是AccountProfile時如圖所示連接解決方​​案。對於我們的用例來說,這並不好。

我們目前使用的是MVC5。

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

    } 
相關問題