title: How to configure the environment of an ASP.NET application?
body: <p>What is the recommended way of allowing an ASP.NET application to know which environment it runs in? My application can run in these environments:</p>
  
  <ul>
  <li>Debugging within Visual Studio</li>
  <li>An automated system test</li>
  <li>Deployment on a staging server</li>
  <li>Deployment on a production server</li>
  </ul>
  
  <p>In each of these environments the application needs some different configuration. The main difference between the environments is which database connection settings to use, but there are also other differences.</p>
  
  <p>This is what I have tried:</p>
  
  <ul>
  <li>I have tried using the "configuration" option in Visual Studio. By default there is two: Release and Debug. I have tried to replace these two with identifiers for my four environments. These configurations can then be used to apply a transform to the Web.config file. The problem here is that choosing the configuration happens on build time, and I would like to compile my application and then choose the environment before running it on a web server. The Web.config transformation also doesn't happen when debugging inside Visual Studio, so instead of telling the application that it runs in the debugging environment, it gets no environment. I found a workaround at <a href="https://stackoverflow.com/questions/3922291/use-visual-studio-web-config-transform-for-debugging">Use Visual Studio web.config transform for debugging</a> but it doesn't seem to work well. I have to change the configuration in the project properties, which is a slow process.</li>
  <li>I have tried using an environment variable. This way I could set a variable MYAPP_ENV=dev from outside the application, and I could read it in C# as<br>
  string env = System.Environment.GetEnvironmentVariable("MYAPP_ENV");<br>
  But then I am not sure how to set this environment variable from within Visual Studio and from within IIS. I cannot set it globally on the machine because the same machine needs to be able to run the application in multiple environments.</li>
  </ul>
  
  <p>So, how is the recommended way of doing this in ASP.NET? In Ruby on Rails I would use the RAILS_ENV environment variable, and in PHP I would include a file, which is not checked into the repository and is added to the ignore list of the version control system.</p>