首先引用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
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
原文地址:https://www.cnblogs.com/mq0036/p/10957010.html
时间: 2024-11-09 08:28:52