首先引用NuGet包
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.Json
- Microsoft.Extensions.DependencyInjection
- Microsoft.Extensions.Options
- Microsoft.Extensions.Options.ConfigurationExtensions
我們先來看一下appsettings.json文件
- {
- "Logging": {
- "IncludeScopes": false,
- "Debug": {
- "LogLevel": {
- "Default": "Warning"
- }
- },
- "Console": {
- "LogLevel": {
- "Default": "Warning"
- }
- }
- },
- "AppSupportDatabase": {
- "ConnectionString": "server=.;initial catalog=TestDB;user id=sa;password=123",
- "ProviderName": "System.Data.SqlClient"
- }
- }
我們想取ProviderName怎么辦呢?首先新建ConfigManager
- public class ConfigManager
- {
- public string ProviderName { get; set; }
- public string ConnectionString { get; set; }
- }
GetAppsettings方法
- public T GetAppsettings<T>(string key) where T : class, new()
- {
- string keyDir = System.IO.Directory.GetCurrentDirectory();
- IConfiguration config = new ConfigurationBuilder()
- .SetBasePath(keyDir)
- .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
- .Build();
- var appconfig = new ServiceCollection()
- .AddOptions()
- .Configure<T>(config.GetSection(key))
- .BuildServiceProvider()
- .GetService<IOptions<T>>()
- .Value;
- return appconfig;
- }
調用例子
- GetAppsettings<ConfigManager>("AppSupportDatabase").ProviderName
出處:https://www.studenty.cn/?p=1094
==========================================
需要先引用官方的nuget包
①:Microsoft.Extensions.Configuration
②:Microsoft.Extensions.Options.ConfigurationExtensions
用戶自定義json的配置文件
在這里我用的配置文件名稱是appsettings.json
配置文件內容如圖所示:
在Startup類中的Startup方法中編輯代碼,我先把代碼貼出來吧:
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
var connString = new ConnectionStrings();
Configuration.GetSection("ConnString").Bind(connString);
在代碼中 ConnectionStrings類是一個Model,然后你創建的變量connString已經被實例化了。你可以訪問了
作者:奧斯卡的肌膚
鏈接:https://www.jianshu.com/p/a13a0194ff91
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。