gpt4 book ai didi

asp.net-core - appsettings..json 未在服务器上使用

转载 作者:行者123 更新时间:2023-12-03 07:26:59 24 4
gpt4 key购买 nike

我在我的项目中定义了以下结构。


appsettings.json
appsettings.development.json
appsettings.prod.json
appsettings.uat.json

程序.cs

    public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
});
webBuilder.UseStartup<Startup>();
});
}

我希望服务器读取阶段特定的应用程序设置文件。但所有环境都始终读取 appsettings.json。

最佳答案

您是否将 appsetting.json 复制到输出目录?

<ItemGroup>
<None Update="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.P.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

如果你想使用环境变量,你应该注册它们.AddEnvironmentVariables()

像这样:

public Startup(IWebHostEnvironment environment)
{
_environment = environment ?? throw new ArgumentNullException(nameof(environment));

Configuration = new ConfigurationBuilder()
.SetBasePath(environment.ContentRootPath)
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{environment.EnvironmentName}.json", true)
.AddEnvironmentVariables()
.Build();
}

我认为只要设置了 DOTNET_ENVIRONMENT,.NET 5 及更高版本就会为您执行此操作。 https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.host.createdefaultbuilder?view=dotnet-plat-ext-7.0&viewFallbackFrom=net-6.0

关于asp.net-core - appsettings.<env>.json 未在服务器上使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67312814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com