迭代ASP.NET MVC视图以查找支持特定模型类型的所有视图

Ted*_*erg 9 c# asp.net reflection asp.net-mvc razor

我想获得支持呈现特定模型类型的所有视图的列表.

伪代码:

IEnumerable GetViewsByModelType(Type modelType)
{
   foreach (var view in SomeWayToGetAllViews())
   {
      if (typeof(view.ModelType).IsAssignableFrom(modelType))
      {
         yield return view; // This view supports the specified model type
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

换句话说,鉴于我有一个MyClass模型,我想找到支持渲染它的所有视图.即@model类型为MyClass的所有视图,或其继承链中的类型.

Far*_*ina 8

根据我的发现,编译的视图不包含在程序集中,因此它不会在公园反射中散步.

在我看来,你最好的选择是列出.cshtml剃刀视图,然后使用BuildManager类来编译类型,这将允许你获得Model属性类型.

以下是查找具有@Model类型的LoginViewModel的所有Razor视图的示例:

var dir = Directory.GetFiles(string.Format("{0}/Views", HostingEnvironment.ApplicationPhysicalPath), 
    "*.cshtml", SearchOption.AllDirectories);

foreach (var file in dir)
{
    var relativePath = file.Replace(HostingEnvironment.ApplicationPhysicalPath, String.Empty);

    Type type = BuildManager.GetCompiledType(relativePath);

    var modelProperty = type.GetProperties().FirstOrDefault(p => p.Name == "Model");

    if (modelProperty != null && modelProperty.PropertyType == typeof(LoginViewModel))
    {
        // You got the correct type
    }
}
Run Code Online (Sandbox Code Playgroud)