在文本生成T4文件中使用Microsoft.AspNetCore dll

时间:2018-12-07 15:05:21

标签: asp.net-mvc t4

我正在尝试使用t4文件为ASP.Core Web API生成一些代码。我需要在var table = document.getElementById("TableID"); for(var i = table.rows.length - 1; i > 0; i--) { table.deleteRow(i); } 文件中执行以下代码

.tt

但是,我总是收到一个错误消息,即找不到命名空间“ Controller”。如何引用此<#@ template debug="false" hostspecific="false" language="C#" #> <#@ assembly name="Microsoft.AspNetCore.Mvc.ViewFeatures.dll" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> <#@ import namespace="System" #> <#@ import namespace="System.Reflection" #> <#@ import namespace="System.Runtime" #> <#@ import namespace="System.IO" #> <#@ import namespace="Microsoft" #> <#@ import namespace="System.Collections.Generic" #> <#@ output extension=".cs" #> <# // put cs code here var asm = Assembly.LoadFrom(Path.Combine(Directory.GetCurrentDirectory(), "D:\\work\\AITeF\\AdministratorModule\\AdministratorModule\\bin\\Debug\\netcoreapp2.1\\AdministratorModule.dll")); var controlleractionlist = asm.GetTypes() .Where(type => typeof(Controller).IsAssignableFrom(type)) .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public)) .Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any()) .Select(x => new { Controller = x.DeclaringType.Name, Action = x.Name, ReturnType = x.ReturnType.Name, Attributes = String.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))) }) .OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList(); #> 来执行我的代码而不会出错。

1 个答案:

答案 0 :(得分:0)

Microsoft.AspNetCore.Mvc.ViewFeatures.dll添加有效路径后,您需要为Controller导入名称空间或对其完全限定

<#@ assembly name="a:\valid\path\to\Microsoft.AspNetCore.Mvc.ViewFeatures.dll" #>
<#@ assembly name="System.Core" #>
// ...
<#@ import namespace="Microsoft.AspNetCore.Mvc.Controller" #>

// or fully qualified
    var controlleractionlist = asm.GetTypes()
        .Where(type => typeof(Microsoft.AspNetCore.Mvc.Controller).IsAssignableFrom(type))