I have my web applications (PRODUCTION, STAGING, TEST) hosted on IIS web server. So it was not possible to rely on ASPNETCORE_ENVIRONMENT operative's system enviroment variable, because setting it to a specific value (for example STAGING) has effect on others applications.
As work-around, I defined a custom file (envsettings.json) within my visualstudio solution:
with 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 application type (Production, Staging or Test) I set this file accordly: supposing I am deploying TEST application, i will have:
"ASPNETCORE_ENVIRONMENT": "Test"
After that, in Program.cs file just retrieve this value and then set the webHostBuilder's enviroment:
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>();
// If none is set it use Operative System hosting enviroment
if (!string.IsNullOrWhiteSpace(enviromentValue))
{
webHostBuilder.UseEnvironment(enviromentValue);
}
var host = webHostBuilder.Build();
host.Run();
}
}
Remember to include the envsettings.json in the publishOptions (project.json):
"publishOptions":
{
"include":
[
"wwwroot",
"Views",
"Areas/**/Views",
"envsettings.json",
"appsettings.json",
"appsettings*.json",
"web.config"
]
},
This solution make me free to have ASP.NET CORE application hosted on same IIS, independently from envoroment variable value.
Properties\launchSettings.json
to simulate another environment for debugging in Visual Studio. – Trilobate