管理调试和释放连接字符串

12 c# vb.net asp.net connection-string

在.NET/SQLServer应用程序中管理调试和释放连接字符串的好方法是什么?

我有两个SQL Server,一个生产和一个构建/调试,我需要一种在部署ASP.NET应用程序时在两者之间切换的方法.

目前我只是将它们存储在web.config中并对其中一个进行注释,但是在部署时容易出错.

Axe*_*ger 14

创建Web.config文件的调试和发布版本,例如Web.debug.config和Web.release.config.然后添加一个预编译条件,根据当前Target将相关版本复制到web.config中.

编辑:要添加预编译条件,请右键单击您的项目并选择"属性",然后转到"构建事件"选项卡,并将以下代码添加到预编译条件中.显然,您必须根据需要修改代码,请参见下图.

@echo off

echo Configuring web.config pre-build event ...

if exist "$(ProjectDir)web.config" del /F / Q "$(ProjectDir)web.config"

if "$(ConfigurationName)" == "Debug Test" goto test
if "$(ConfigurationName)" == "Debug M" goto M
if "$(ConfigurationName)" == "Debug BA" goto BA
if "$(ConfigurationName)" == "Release Test" goto test
if "$(ConfigurationName)" == "Release M" goto M
if "$(ConfigurationName)" == "Release BA" goto BA

echo No web.config found for configuration $(ConfigurationName). Abort batch.
exit -1
goto :end

:test
copy /Y "$(ProjectDir)web.config.test" "$(ProjectDir)web.config"
GOTO end

:BA
copy /Y "$(ProjectDir)web.config.BA" "$(ProjectDir)web.config"
GOTO end

:M
copy /Y "$(ProjectDir)web.config.M" "$(ProjectDir)web.config"
GOTO end

:end
echo Pre-build event finished
Run Code Online (Sandbox Code Playgroud)

项目属性http://img442.imageshack.us/img442/1843/propsa.jpg


Hen*_*man 8

好消息是.NET4有这样的规定,你可以为每个配置(web.Release.config,web.Debug.config)分别配置.

坏消息是......你可能还没有使用它.


Sam*_*bes 5

使用预处理器指令:当您的项目配置为在调试模式下运行时,将选择调试连接字符串,否则将自动选择发布连接字符串。

在 Visual Studio 中,您会注意到语句专门根据项目配置(调试或发布)而变暗。

只需在您的代码中添加类似以下内容:

string myConnectionString;
#if DEBUG
     myConnectionString = "your debug connection string";//may be read from your debug connection string from the config file
#else
     myConnectionString = "your release connection string"; //may be read from your relase connection string from the config file
#endif
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请检查