T4模板和Server.MapPath

aza*_*arp 3 t4

我试图使用T4模板获取Views文件夹中的文件夹名称,它不断给我以下错误:

错误3编译转换:当前上下文中不存在名称"Server"c:\ Projects\LearningASPMVC\LearningASPMVCSolution\LearningMVC\StronglyTypedViews.tt 20 47
错误4命名空间不直接包含字段或方法等成员C:\ Projects\LearningASPMVC\LearningASPMVCSolution\LearningMVC\StronglyTypedViews.cs 1 1 LearningMVC

这是T4模板:

<#@ template language="C#" debug="True" hostspecific="True" #>
<#@ output extension=".cs" #>

<#@ assembly name="System.Web" #>

<#@ import namespace="System.IO" #>
<#@ import namespace="System.Web" #>


using System; 



namespace StronglyTypedViews 
{

    <# 

     string[] folders = Directory.GetDirectories(Server.MapPath("Views")); 

     foreach(string folderName in folders) 
     {

     #>  

     public static class <#= folderName #> { } 


     <# } #>        

}
Run Code Online (Sandbox Code Playgroud)

更新:使用物理路径工作:

<#@ template language="C#" debug="True" hostspecific="True" #>
<#@ output extension=".cs" #>

<#@ assembly name="System.Web" #>
<#@ assembly name="System.Web.Mvc" #>


<#@ import namespace="System.Web.Mvc" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Web" #>


using System; 

namespace StronglyTypedViews 
{

    <# 

     string viewsFolderPath = @"C:\Projects\LearningASPMVC\LearningASPMVCSolution\LearningMVC\"; 

     string[] folders = Directory.GetDirectories(viewsFolderPath + "Views");


     foreach(string folderName in folders) 
     {

     #> 

     public static class <#= System.IO.Path.GetFileName(folderName) #> {         
     <#      
      foreach(string file in Directory.GetFiles(folderName))      {
         #>          
         public const string <#= System.IO.Path.GetFileNameWithoutExtension(file) #> = "<#= System.IO.Path.GetFileNameWithoutExtension(file).ToString()  #>";

     <# } #>



     <#  } #>

     }




}
Run Code Online (Sandbox Code Playgroud)

Ore*_*ner 12

T4模板在visual studio创建的临时上下文中执行,并且远远超出Web应用程序.该临时上下文用于生成输出文本文件.它不是任何方式的Web应用程序,与您正在创作的Web应用程序无关.因此,System.Web.HttpContext没有分配任何值,并且无法调用MapPath().

Environment.CurrentDirectory也没有多大帮助,因为模板在某个临时文件夹中执行.

你能做什么?如果您可以使用绝对路径,请继续执行此操作.否则,在<#@ template#>指令中添加hosts特许属性将允许您使用Host变量及其ResolvePath()方法.ResolvePath 允许您解析相对于TT文件本身的路径.

例如(example.tt):

<#@ template language="C#" hostspecific="True" #>
<#@ output extension=".cs" #>
// <#=Host.ResolvePath(".")#>
Run Code Online (Sandbox Code Playgroud)

输出(example.cs):

// C:\Users\myusername\Documents\Visual Studio 2008\Projects\MvcApplication1\MvcApplication1\.
Run Code Online (Sandbox Code Playgroud)

Oleg Sych关于模板指令的帖子有一个关于hostspecific属性的部分.