导航

web api appsettings.json 数据库连接

Posted on 2021-07-26 18:12  yiyishuitian  阅读(344)  评论(0编辑  收藏  举报
  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"];