如何从TypeScript中的web.config获取密钥?

时间:2016-06-23 19:41:23

标签: typescript web-config key

如何从API项目中的web.config获取密钥到我的TypeScript UI项目中?我已经尝试了以下但没有任何东西可以访问我可以告诉的配置文件:

 apiUrl: string = '@System.Configuration.ConfigurationManager.AppSettings["ApiUrl"]';

这也不起作用:

 apiUrl: string = "@ConfigurationManager.AppSettings['ApiUrl']";

我也尝试了单引号或双引号的每种组合,但无济于事。有关如何从TypeScript中的web.config文件获取值的任何见解?

1 个答案:

答案 0 :(得分:0)

尝试从其他程序集/项目访问配置文件通常不是一个好主意,因为它们在编译时通常不会输出到同一目录。

因为TypeScript被转换为JavaScript,所以无论它位于何处,都无法直接从配置文件中读取。

如果要动态更改服务的URL(例如从DEV端点到QA或生产端点),可以在HTML / CSHTML文件中使用 Razor语法来获取值从配置文件中,然后值注入脚本, OR ,您可以在部署期间使用 Powershell 来替换TypeScript文件中的值在构建过程中。

# Argument passed into PowerShell script (or write out URL string manually).
$NewURL1 = $args[0];
$NewURL2 = "http://goodURL.com/api";

# *.js files, because your *.ts files will already be transpiled.
$files = gci "C:\MyProject\DropFolder" -recurse -include "exampleWithBadURL.js", "otherFile.js";

Foreach ($file in $files)
{
    $fileContent = Get-Content($file) -Raw;
    attrib $file -r;

    # Perform the replacement.
    $fileContent -replace "http://localhost:38774/", $NewURL1 | Out-File $file;
    $fileContent -replace "http://badURL.com/api/", $NewURL2 | Out-File $file;

    Write-Output($file.FullName);
}

如果您的构建/发布代理允许,您可以在将代码部署到特定环境时运行此Powershell脚本。我在我的版本定义中 VSTS / TFS 中使用类似的脚本 我将文件复制过来。