如何使用Nant在构建时自动更改连接字符串

ryu*_*ice 8 .net nant

当使用Nant发布构建类型时,是否可以自动更改web.config中的连接字符串?如果是这样,怎么样?谢谢

wen*_*ang 18

我想你可以使用xmlpoke任务.例如,如果您的web.config是

<?xml version="1.0"?>
<configuration>
    <connectionStrings>
        <add name="myDb" connectionString="blah" providerName="blah"/>
    </connectionStrings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样在你的构建文件中添加一个任务.

<xmlpoke 
    file="path_to_your_web_root\Web.config"
    xpath="/configuration/connectionStrings/add[@name='myDb']/@connectionString"
    value="your_connection_string" />
Run Code Online (Sandbox Code Playgroud)

哦,这是xmlpoke任务的文档.http://nant.sourceforge.net/release/latest/help/tasks/xmlpoke.html


Fre*_*örk 5

我假设你想要这样做,以便在Nant构建发布代码时让连接字符串指出生产环境而不是开发或测试环境.我通常有不同的方法来解决这个问题; 将连接字符串保存在单独的文件中.您可以使用以下configSource属性执行此操作:

<!-- point out a file containing the connectionStrings config section -->
<connectionStrings configSource="connections.config"></connectionStrings>
Run Code Online (Sandbox Code Playgroud)

connections.config文件应如下所示:

<?xml version="1.0"?>
<connectionStrings>
    <add name="myDb" connectionString="{your connection string}"/>
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)

由于连接字符串在生产环境中很少更改,因此connections.config通常可以从部署中排除该文件.