1.Nuget添加Microsoft.Extensions.Configuration.Json 2.appsettings.json中添加"ConnectionStrings" { "Logging": { "LogLevel": { "Default": "Warning" } }, "ConnectionStrings": { "SQLConnection": "Data Source=127.0.0.1;Database=xxxx;UID=xx;P
1.Nuget添加Microsoft.Extensions.Configuration.Json
2.appsettings.json中添加"ConnectionStrings"
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": { "SQLConnection": "Data Source=127.0.0.1;Database=xxxx;UID=xx;PWD=xx;", "OracleConnection": "", "MySqlConnection": "", "SqlLiteConnection": "" },
"AllowedHosts": "*"
}
3.新建AppSettingsJson.cs
using Microsoft.Extensions.Configuration; using System.IO; namespace WebAPI { public 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.C#调用
var config = AppSettingsJson.GetAppSettings(); var str = config.GetSection("ConnectionStrings:SQLConnection").Value;