我有一个 .Net core 3.1 Worker 服务,但每当我运行它时,我都会将环境名称设为“Production”,并将 appsettings.json 作为其文件以从中读取配置。我想将此服务部署到 Windows 服务器,我已将 ASPNETCORE_ENVIRONMENT 变量添加为“SIT”(测试环境),但它仍然使用 appsettings.json 而不是 appsettings.SIT.json 。
我的 API 项目遇到了同样的问题,但是使用了 dotnet cli 进行发布,它在 web.config 中创建了环境条目,这对我有用。但由于这是一个控制台应用程序,我被严重卡住了。我可以在这里得到一些帮助吗
我用于 api 的命令 - “dotnet publish /p:Configuration=Release /p:EnvironmentName=SIT”
在下面找到我用来读取环境名称的代码。
公共静态字符串 CURRENT_DIR = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
static void Main(string[] args)
{
var builder = new ConfigurationBuilder();
BuildConfig(builder);
CreateHostBuilder(args).Build().Run();
}
static void BuildConfig(IConfigurationBuilder builder)
{
builder.SetBasePath(CURRENT_DIR)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{ Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
IConfiguration Configuration = hostContext.Configuration;
var collection = new ServiceCollection();
collection.AddOptions();
collection.Configure<AppOptions>(Configuration.GetSection("AppOptions"));
services.AddHttpContextAccessor();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
var env = serviceProvider.GetRequiredService<IHostEnvironment>();
ConfigureLogging(env);