I have web applications (PRODUCTION, START, TEST) hosted on the IIS web server. Thus, it was not possible to rely on the ASPNETCORE_ENVIRONMENT life-support environment variable, since setting it to a specific value (for example, STAGING) affects other applications.
In the process, I defined a custom file (envsettings.json) in my visualstudio solution:

with the following content:
{ // Possible string values reported below. When empty it use ENV variable value or Visual Studio setting. // - Production // - Staging // - Test // - Development "ASPNETCORE_ENVIRONMENT": "" }
Then, based on my type of application (Production, Staging or Test), I install this file as follows: suppose I deploy the TEST application, I will have:
"ASPNETCORE_ENVIRONMENT": "Test"
After that, just extract this value in the Program.cs file, and then set up the webHostBuilder environment:
public class Program { public static void Main(string[] args) { var currentDirectoryPath = Directory.GetCurrentDirectory(); var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json"); var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath)); var enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString(); var webHostBuilder = new WebHostBuilder() .UseKestrel() .CaptureStartupErrors(true) .UseSetting("detailedErrors", "true") .UseContentRoot(currentDirectoryPath) .UseIISIntegration() .UseStartup<Startup>();
Remember to include envsettings.json in publishOptions (project.json):
"publishOptions": { "include": [ "wwwroot", "Views", "Areas/**/Views", "envsettings.json", "appsettings.json", "appsettings*.json", "web.config" ] },
This solution allows me to have an ASP.NET CORE application hosted on the same IIS, regardless of the value of the envoroment variable.