<!-- Custom property group added to add the environment name during publish
The EnvironmentName property is used during the publish
for the environment variable in web.config
-->
<PropertyGroup Condition=" '$(Configuration)' == '' Or '$(Configuration)' == 'Debug'">
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' != '' AND '$(Configuration)' != 'Debug' ">
<EnvironmentName>Production</EnvironmentName>
</PropertyGroup>
public class Program
{
public static void Main(string[] args)
{
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
{
// Possible string values reported below. When empty, it uses the ENV variable value or
// Visual Studio setting.
// - Production
// - Staging
// - Test
// - Development
"ASPNETCORE_ENVIRONMENT": "Development"
}
稍后修改 程序文件,如下所示
public class Program
{
public static IConfiguration Configuration { get; set; }
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 environmentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
var webHostBuilder = new WebHostBuilder()
.UseKestrel()
.CaptureStartupErrors(true)
.UseContentRoot(currentDirectoryPath)
.UseIISIntegration()
.UseStartup<Startup>();
// If none is set it use Operative System hosting enviroment
if (!string.IsNullOrWhiteSpace(environmentValue))
{
webHostBuilder.UseEnvironment(environmentValue);
}
var host = webHostBuilder.Build();
host.Run();
}
}
static async Task Main(string[] args)
{
...
//set the environment variable based on App Settings
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
builder.UseEnvironment(environment);