gpt4 book ai didi

T4 模板和 Server.MapPath

转载 作者:行者123 更新时间:2023-12-04 03:05:30 28 4
gpt4 key购买 nike

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

错误 3 编译转换:名称“服务器”在当前上下文中不存在 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() #>";

<# } #>



<# } #>

}




}

最佳答案

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's post about the template directive有一个关于主机特定属性的部分。

关于T4 模板和 Server.MapPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2044327/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com