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:
- Debugging within Visual Studio
- An automated system test
- Deployment on a staging server
- Deployment on a production server
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.
This is what I have tried:
- 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 Use Visual Studio web.config transform for debugging but it doesn't seem to work well. I have to change the configuration in the project properties, which is a slow process.
- 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
string env = System.Environment.GetEnvironmentVariable("MYAPP_ENV");
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.
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.