web api appsettings.json 数据库连接

  1. 编辑AppSettings.Json
    1.   "ConnectionStrings": {
          "DefaultConnection": "Data Source=.;Initial Catalog=DataBaseName;User Id=UserName;Password=Password;"
        }

       

  2. 引用 Microsoft.Extensions.Configuration
  3. 创建 类 AppSettingsJson.cs
    1.     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();
              }
      
          }

       

  4. 使用 
            var appSettingsJson = AppSettingsJson.GetAppSettings();
            //方法一
            var connectionString = appSettingsJson["ConnectionStrings:DefaultConnection"];
            //方法二
            var connectionString = appSettingsJson.GetConnectionString("DefaultConnection");
            //方法三
            var connectionString = appSettingsJson.GetSection("ConnectionStrings")["DefaultConnection"];

 

web api appsettings.json 数据库连接

上一篇:uniapp自定义属性 -- 小坑记录 获取不到自定义属性


下一篇:Python数据持久化-MongoDB篇