.NET Core appsettings.json 获取数据库连接字符串_枯叶轮回的博客-CSDN博客

来源: .NET Core appsettings.json 获取数据库连接字符串_枯叶轮回的博客-CSDN博客

本文主要介绍.NET Core中,通过appsettings.json配置文件获取数据库连接字符串

 

1、在项目的根目录中创建appsettings.json文件

{
  "MssqlConnectionString": "Server=yourip; Database=yourdbname; User Id=yourusername; Password=yourpassword; Pooling=true;",
  "Db2ConnectionString": "Database=yourdbname;UserID=yourusername;Password=yourpassword;Server=yourip:yourport",
  "SomeOtherKey": "SomeOtherValue"
}

2、安装Microsoft.Extensions.Configuration.Json的Nuget包

Install-Package Microsoft.Extensions.Configuration.Json -Version 2.2.0

3、添加AppSettingsJson类

using Microsoft.Extensions.Configuration;
using System.IO;
namespace RutarBackgroundServices.AppsettingsJson
{
    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、使用AppSettingsJson获取连接字符串

var appSettingsJson = AppSettingsJson.GetAppSettings();
//方法一
var connectionString = appSettingsJson.GetConnectionString("MssqlConnectionString");
//方法二
var connectionString = appSettingsJson["MssqlConnectionString"];
赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏