简体   繁体   中英

How to define web.config local variables

I have a web application in C# with .NET Framework 4.0 and I'm trying to find a way to define a variable in Web.Config that can be referenced elsewhere within the Web.Config.

I want something like this.

<?xml version="1.0" encoding="utf-8"?>
<LocalWebConfigVars>
    <add key="Var1" value="ServerName1"/>
    <add key="Var2" value="DatabaseName1"/>
</LocalWebConfigVars>
<configuration>
    <connectionStrings>
        <add name="AppConnectionString" connectionString="DATA SOURCE=@Var2 ServerName=@Var1"/>
        <add name="OtherStuff" value="@Var1"/>
etc...

Currently I have to keep 3 or 4 hard-coded values (some embedded others just the value) updated to the same thing and would like to make it easier to keep in sync.

Is this possible?

Thanks.

Edit:

Just some background. The reason this is becoming problematic is that we define the apps database instance (among other instance specific setting) in the web.config. We have multiple database instances in our test and production environments and if I need to switch to a different one them while testing something and miss one of the hand full of references I get some strange results. I'm trying to avoid this by defining it once and referencing it everywhere else.

Would not doing a simply .config transformation for each of your environments work, by setting up a project configuration & transform, you would be able to swap from environment to environment by the use of solutions configuration dropdown.

See this link for more info on transforms on .config files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM