如何从.tt文件中读取web.config中的appSetting(T4模板)

时间:2017-09-26 06:26:09

标签: c# asp.net code-generation t4

我正在尝试在web.config文件中提供一个URL,在编译我的web项目上的.tt文件之前,构建系统将更新该URL。

我的.tt文件的相关部分如下:

<#@ template debug="true" hostSpecific="true" language="C#" #>
<#@ output extension=".ts" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ Assembly Name="System.Configuration.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Configuration" #>
<#@ import namespace="System.Collections.Specialized" #>

import { Injectable } from "@angular/core";

<#= RegisterNameSpace("Server.Web.Dashboard.Models.APIRequest") #>
<#= RegisterNameSpace("Server.Web.Dashboard.Models.APIResponse") #>
<#= RegisterNameSpace("Server.Web.Dashboard.Models.APIGeneric") #>
<#= RegisterNameSpace("Server.Data.POCODataObjects") #>

@Injectable()
export class WebServiceCommunicatorService {

    rootUrl : string = '<#= ConfigurationManager.AppSettings["ServerServiceURL"] #>';

.....

当我尝试从.tt文件生成.ts文件时,收到以下错误消息:

Severity    Code    Description Project File    Line    Suppression State
Error       An expression block evaluated as Null
System.ArgumentNullException: Value cannot be null.
Parameter name: objectToConvert
   at Microsoft.VisualStudio.TextTemplating.ToStringHelper.ToStringWithCulture(Object objectToConvert)
   at Microsoft.VisualStudio.TextTemplatingF553823B88CD6076D80EB08F6EA809752D0E5DC3E61C0FA53FB2F9AC22ACABF3B7BB9C8801A54E5DBC2A556C03FA42F2EA2AFCE58B708BEC94B0968193987868.GeneratedTextTransformation.TransformText() in webservicecommunicator.service.tt:line 35    Dashboard   webservicecommunicator.service.tt   35  

3 个答案:

答案 0 :(得分:3)

我已经假装该文件是XML文件而不是配置文件。首先,我找到web.config的绝对路径,然后加载它并读取节点。

首先是依赖性:

json_decode($_POST['data'])

所以这是我的尝试:

<#@ Assembly Name="System.Web.dll" #>
<#@ Assembly Name="System.Configuration.dll" #>
<#@ assembly name="System.Xml" #>

<#@ import namespace="System.Configuration" #>
<#@ import namespace="System.Web.Configuration" #>
<#@ import namespace="System.Collections.Specialized" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.IO" #>

答案 1 :(得分:1)

您可以尝试使用ConfigurationManager.OpenExeConfiguration(path)方法打开硬编码路径(不确定是否可以执行相对路径)。此时,您可以使用返回的Configuration对象自己的AppSettings属性。

答案 2 :(得分:1)

添加System.Configuration程序集并将其导入您的模板文件,如下所示。这将允许您使用ConfigurationManager引用AppSettings。

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Configuration" #>
<#@ import namespace="System.Configuration" #>

<#
    var myVariable = ConfigurationManager.AppSettings["MyConfigSetting"];

    ... more code here
#>
相关问题