2017-02-09 62 views
0

我想從我的解決方案中使用反射的任何控制器返回ActionResult的所有公共方法的列表,但我遇到了一些奇怪的行爲。在解決方案中迭代控制器

Assembly asm = Assembly.GetAssembly(typeof(MyDLL.MvcApplication)); 

var controllerActionList = asm.GetTypes().ToList(); 

如果我運行上面的代碼讓我的所有類型,包括我所有的模型和控制器等,就像我所期望的列表。但是,如果我修改它並運行下面的代碼,我的結果列表將回到空白。任何想法這裏發生了什麼?我會認爲這應該過濾類型,所以我得到一個所有的控制器的列表嗎?

Assembly asm = Assembly.GetAssembly(typeof(MyDLL.MvcApplication)); 

var controllerActionList = asm.GetTypes() 
    .Where(type => typeof(Controller).IsAssignableFrom(type)).ToList(); 
+0

你的代碼真的應該工作的控制每一個公共方法的成對列表。而不是typeof(控制器),你可以嘗試typeof(System.Web.Mvc.Controller)?然後,真的應該報告System.Web.Mvc.Controller的任何子類。 –

+0

雅我已經嘗試過,它沒有工作,但我得到它以奇怪的方式工作。我認爲這個項目使用的.net版本與目標dll使用的版本不完全相同,導致類型比較總是失敗。請在下面查看我的答案,瞭解我如何按照自己的意願完成任務。謝謝您的幫助! –

回答

0

我通過使用下面的代碼得到它的工作。我認爲直接類型比較對我來說是失敗的,因爲我相信我在這兩個項目之間有兩個不同的.net版本。

Assembly asm = Assembly.GetAssembly(typeof(SCCView.MvcApplication)); 

var controllerActionList = asm.GetTypes() 
    .Where(type => type.BaseType.Name == "Controller") 
    .SelectMany(type => type.GetMethods()) 
    .Where(
     m => m.IsPublic && m.ReturnType.Name == "ActionResult") 
    .Select(x => new {Controller = x.DeclaringType.Name, Action = x.Name}) 
    .OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList(); 

上述會給你返回一個ActionResult