.net core 6发布配置文件以替换Visual Studio中的appsettings。

huangapple go评论78阅读模式
英文:

.net core 6 publish profiles to replace appsettings with visual studio

问题

我正在为.NET Core 6控制台应用程序编写代码,我想在发布时将appsettings.json文件替换为appsettings.envname.json,并根据发布配置使用不同的appsettings。我该如何在Visual Studio中实现这个目标?

英文:

I am writing a .NET core 6 console application for which I would like to replace the appsettings.json file to appsettings.envname.json whenever I publish for envname.

The file should be named appsettings.json basically based on the publish profile I would like to use a different appsettings.

How can I do that in Visual Studio?

答案1

得分: 1

在控制台应用程序中,您可以在Program.cs文件中编写以下内容:

var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder()
                     .SetBasePath(Environment.CurrentDirectory)
                     .AddJsonFile("appsettings.json", false, true)
                     .AddJsonFile($"appsettings.{environmentName}.json", true)
                     .AddEnvironmentVariables();
Configuration = builder.Build();

请注意,这是代码的翻译部分。

英文:

In console application you can write into your Program.cs:

var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder()
                     .SetBasePath(Environment.CurrentDirectory)
                     .AddJsonFile("appsettings.json", false, true)
                     .AddJsonFile($"appsettings.{environmentName}.json", true)
                     .AddEnvironmentVariables();
Configuration = builder.Build();

huangapple
  • 本文由 发表于 2023年6月1日 04:34:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377086.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定