IHostingEnvironment
您应该使用两个接口。一种用于ASP.NET Core应用程序,另一种用于.NET Core控制台应用程序。您可以同时使用以下代码示例:
using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting.Internal;
namespace MyApplication.Common
{
public static class ConfigurationFactory
{
public static IConfigurationBuilder Configure(IConfigurationBuilder config, IHostingEnvironment env)
{
return Configure(config, env.EnvironmentName);
}
private static IConfigurationBuilder Configure(IConfigurationBuilder config, Microsoft.Extensions.Hosting.IHostingEnvironment env)
{
return Configure(config, env.EnvironmentName);
}
private static IConfigurationBuilder Configure(IConfigurationBuilder config, string environmentName)
{
return config
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
}
public static IConfiguration CreateConfiguration()
{
var env = new HostingEnvironment
{
EnvironmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"),
ApplicationName = AppDomain.CurrentDomain.FriendlyName,
ContentRootPath = AppDomain.CurrentDomain.BaseDirectory,
ContentRootFileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory)
};
var config = new ConfigurationBuilder();
var configured = Configure(config, env);
return configured.Build();
}
}
}
new ConfigurationBuilder().AddEnvironmentVariables()
和查找ASPNETCORE_ENVIRONMENT
。