关于.Net Core使用appsettings.json中连接数据库字符串

1、写入数据库连接字符串
  比如:

"ConnectionStrings": {
    "Conn": "Data Source=.;Initial Catalog=TestDome;Integrated Security=True"
  }

2、新建 AppsettingJson.cs 类

  例如:

public class AppSettingsJson
    {
        public static IConfiguration Configuration { get; set; }

        static AppSettingsJson()
        {
            //ReloadOnChange = true 当appsettings.json被修改时重新加载            
            Configuration = new ConfigurationBuilder()
            .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
            .Build();
        }
    }

3、选择变量接受数据库连接字符串

  例如:

var ConnectionString =  AppSettingsJson.Configuration.GetConnectionString("Conn");

4、此时的ConnectionString中已经包含了有关于Conn中所定义的字符串。

posted @ 2022-06-19 14:23  森雾  阅读(1532)  评论(0编辑  收藏  举报