Asp.net-Mvc

如何通過傳遞 ControllerName 獲取 MVC Controller 的所有操作列表?

  • February 5, 2017

如何獲取 Controller 的所有操作的列表?我搜尋但找不到範例/答案。我看到一些建議使用反射的範例,但我不知道如何。

這是我正在嘗試做的事情:

public List<string> ActionNames(string controllerName){




}

您還沒有告訴我們為什麼需要這個,但一種可能性是使用反射:

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

顯然,我們知道反射不是很快,所以如果你打算經常呼叫這個方法,你可以考慮通過記憶體控制器列表來改進它,以避免每次都獲取它,甚至記憶給定輸入參數的方法。

引用自:https://stackoverflow.com/questions/11300327