T4模板和Server.MapPath

3
我正在尝试使用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 #> { } 


     <# } #>        

}

更新:使用物理路径已经解决了问题:

<#@ 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()  #>";

     <# } #>



     <#  } #>

     }




}

问题在于HttpContext.Current为空! - azamsharp
1个回答

12

T4模板在Visual Studio创建的临时环境中执行,完全独立于您的Web应用程序之外。该临时环境旨在生成输出文本文件,并不是Web应用程序,与您正在编写的Web应用程序无关。因此,System.Web.HttpContext并没有分配任何值,也不能调用MapPath()

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

那么该怎么办呢?如果您可以使用绝对路径,请直接使用。否则,在<#@ template#>指令中添加hostspecific属性将允许您使用Host变量及其ResolvePath()方法。ResolvePath可让您解析相对于TT文件本身的路径。

例如(example.tt):

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

输出 (example.cs):

// C:\Users\myusername\Documents\Visual Studio 2008\Projects\MvcApplication1\MvcApplication1\.

Oleg Sych的这篇关于模板指令的文章有一个关于hostspecific属性的部分。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接