在.NET Core中,配置管理是通过Microsoft.Extensions.Configuration命名空间提供的
dotnet add package Microsoft.Extensions.Configuration
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
var connectionString = configuration.GetConnectionString("DefaultConnection");
Console.WriteLine($"Connection String: {connectionString}");
}
}
}
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDevDatabase;Trusted_Connection=True;"
}
}
接下来,在Program.cs中添加对环境变量的支持:
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
.Build();
var connectionString = configuration.GetConnectionString("DefaultConnection");
Console.WriteLine($"Connection String: {connectionString}");
}
}
}
现在,当你运行应用程序时,它将根据ASPNETCORE_ENVIRONMENT环境变量的值加载相应的配置文件。例如,如果你将ASPNETCORE_ENVIRONMENT设置为"Development",则应用程序将使用appsettings.Development.json中的连接字符串。如果未设置ASPNETCORE_ENVIRONMENT或其值为"Production",则应用程序将使用appsettings.json中的连接字符串。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。