- 编辑AppSettings.Json
-
"ConnectionStrings": { "DefaultConnection": "Data Source=.;Initial Catalog=DataBaseName;User Id=UserName;Password=Password;" }
-
- 引用 Microsoft.Extensions.Configuration
- 创建 类 AppSettingsJson.cs
-
public static class AppSettingsJson { public static string ApplicationExeDirectory() { var location = System.Reflection.Assembly.GetExecutingAssembly().Location; var appRoot = Path.GetDirectoryName(location); return appRoot; } public static IConfigurationRoot GetAppSettings() { string applicationExeDirectory = ApplicationExeDirectory(); var builder = new ConfigurationBuilder() .SetBasePath(applicationExeDirectory) .AddJsonFile("appsettings.json"); return builder.Build(); } }
-
- 使用
var appSettingsJson = AppSettingsJson.GetAppSettings(); //方法一 var connectionString = appSettingsJson["ConnectionStrings:DefaultConnection"]; //方法二 var connectionString = appSettingsJson.GetConnectionString("DefaultConnection"); //方法三 var connectionString = appSettingsJson.GetSection("ConnectionStrings")["DefaultConnection"];