您好,登錄后才能下訂單哦!
在.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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。