[WebApi]appsettings.json 数据库连接

Posted 厦门德仔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[WebApi]appsettings.json 数据库连接相关的知识,希望对你有一定的参考价值。

1.编辑AppSettings.Json

WebApi项目中的AppSettings.Json, 笔者学习时在实体库新建一个json文件读取不到

"ConnectionStrings": 
    "DefaultConnection": "Data Source=.;Initial Catalog=DataBaseName;User Id=UserName;Password=Password;"
  

2.引用 Microsoft.Extensions.Configuration 相关包

nuget 引用以下三个包

Microsoft.Extensions.Configuration

Microsoft.Extensions.Configuration.FileExtensions

Microsoft.Extensions.Configuration.Json

3.创建 类 AppSettingsJson.cs

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"];

以上是关于[WebApi]appsettings.json 数据库连接的主要内容,如果未能解决你的问题,请参考以下文章

为asp.net核心中的开发和发布环境自动设置appsettings.json?

.NET Core 应用程序中的 appsettings.json 与 appsettings.Environment.json

用 appsettings.Production.json 中的设置覆盖 appsettings.json 中的数组设置

.NET Core WebApi接口ip限流实践

appsettings.json 和 runtimeconfig.json 有啥区别?

读取 appsettings.json