First reference NuGet package
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.Json
- Microsoft.Extensions.DependencyInjection
- Microsoft.Extensions.Options
- Microsoft.Extensions.Options.ConfigurationExtensions
Let's look appsettings.json file
- {
- "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"
- }
- }
We would like to take ProviderName how to do it? First, a new ConfigManager
- public class ConfigManager
- {
- public string ProviderName { get; set; }
- public string ConnectionString { get; set; }
- }
GetAppsettings way
- 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;
- }
Examples of call
- GetAppsettings<ConfigManager>("AppSupportDatabase").ProviderName
Source: https://www.studenty.cn/?p=1094
==========================================
We need to quote the official nuget package
①:Microsoft.Extensions.Configuration
②:Microsoft.Extensions.Options.ConfigurationExtensions
User-defined profiles json
Here profile name I use appsettings.json
Content profile as shown:
In the Startup method Startup class in the code editor, I put the code posted Come:
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);
In the code ConnectionStrings class is a Model, and then you create connString variable has been instantiated. You can visit
Author: Oscar skin
link: https: //www.jianshu.com/p/a13a0194ff91
Source: Jane book
Jane book copyright reserved by the authors, are reproduced in any form, please contact the author to obtain authorization and indicate the source.