You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET中如何默认不使用appsettings.Production配置文件

问题:DOTNET_ENVIRONMENT变量被忽略,始终加载生产配置

需求与问题

需求:默认使用测试服务器配置,仅在生产服务器时加载生产配置。
问题:DOTNET_ENVIRONMENT变量完全被忽略,无论手动指定还是通过环境变量设置,程序始终加载appsettings.Production.json的配置。

配置文件

appsettings.json

{
  "EnvTest": "Test"
}

appsettings.Production.json

{
  "EnvTest": "Production"
}

现有代码(Program.cs)

using Serilog;
using System.Runtime.InteropServices;

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddWindowsService(options =>
{
    options.ServiceName = "test";
});

builder.Environment.EnvironmentName = Environment.GetEnvironmentVariable("DOTNET_Environment") ?? "Default";

// 仅生产服务器覆盖默认配置
if(builder.Environment.IsProduction())
{
    builder.Configuration.AddJsonFile("appsettings.Production.json", optional: false, reloadOnChange: true);
}

Log.Information($"Starting service as {builder.Environment.EnvironmentName} with setting {builder.Configuration.GetValue<string>("EnvTest")} on {RuntimeInformation.FrameworkDescription}");

var host = builder.Build();
host.Run();

测试情况

服务器设置DOTNET_ENVIRONMENT="Test",程序输出:

Starting service as Defaulted with setting Production on .NET 8.0.3

解决办法

1. 修正环境变量读取的拼写错误

官方标准环境变量名为DOTNET_ENVIRONMENT(全大写),原代码中使用DOTNET_Environment(驼峰式)可能导致无法正确读取变量值,统一改为全大写名称。

2. 调整环境名称的设置时机

Host.CreateApplicationBuilder(args)在创建时就已完成环境检测和初始配置加载,后续修改builder.Environment.EnvironmentName不会触发配置重新加载。需在创建Builder前就指定环境名称。

3. 利用默认配置加载逻辑,移除手动加载代码

Host.CreateApplicationBuilder会自动根据当前环境加载对应配置文件:

  • 始终加载appsettings.json
  • 若环境为Production,自动加载appsettings.Production.json并覆盖前者的配置项
  • 其他环境仅加载appsettings.json,刚好符合"默认用测试配置,仅生产环境加载生产配置"的需求

修正后的完整代码

using Serilog;
using System.Runtime.InteropServices;

// 先获取环境变量,默认设为Test(符合需求的默认测试环境)
var envName = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Test";

// 创建Builder时指定环境名称,确保配置加载时使用正确环境
var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings
{
    EnvironmentName = envName
});

builder.Services.AddWindowsService(options =>
{
    options.ServiceName = "test";
});

// 无需手动添加生产配置,依赖Builder的默认加载逻辑即可
Log.Information($"Starting service as {builder.Environment.EnvironmentName} with setting {builder.Configuration.GetValue<string>("EnvTest")} on {RuntimeInformation.FrameworkDescription}");

var host = builder.Build();
host.Run();

验证预期

  • 当DOTNET_ENVIRONMENT设为Test时,输出:Starting service as Test with setting Test on .NET 8.0.3
  • 当DOTNET_ENVIRONMENT设为Production时,输出:Starting service as Production with setting Production on .NET 8.0.3

内容的提问来源于stack exchange,提问作者Bazeon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 00:13:16