首页 > 移动平台 > 详细

web api appsettings.json 数据库连接

时间:2021-07-26 22:44:52      阅读:30      评论:0      收藏: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"];

 

web api appsettings.json 数据库连接

原文:https://www.cnblogs.com/BinBinGo/p/15062784.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!