"ConnectionStrings": { "DefaultConnection": "Data Source=.;Initial Catalog=DataBaseName;User Id=UserName;Password=Password;" }
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"];
web api appsettings.json 数据库连接
原文:https://www.cnblogs.com/BinBinGo/p/15062784.html