从Asp.net core 2.2到以上版本,你可以编写如下代码:
步骤1。创建一个AppSettings类文件。
这个文件包含一些帮助从appsettings中按键获取值的方法。json文件。如下代码所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ReadConfig.Bsl
{
public class AppSettings
{
private static AppSettings _instance;
private static readonly object ObjLocked = new object();
private IConfiguration _configuration;
protected AppSettings()
{
}
public void SetConfiguration(IConfiguration configuration)
{
_configuration = configuration;
}
public static AppSettings Instance
{
get
{
if (null == _instance)
{
lock (ObjLocked)
{
if (null == _instance)
_instance = new AppSettings();
}
}
return _instance;
}
}
public string GetConnection(string key, string defaultValue = "")
{
try
{
return _configuration.GetConnectionString(key);
}
catch
{
return defaultValue;
}
}
public T Get<T>(string key = null)
{
if (string.IsNullOrWhiteSpace(key))
return _configuration.Get<T>();
else
return _configuration.GetSection(key).Get<T>();
}
public T Get<T>(string key, T defaultValue)
{
if (_configuration.GetSection(key) == null)
return defaultValue;
if (string.IsNullOrWhiteSpace(key))
return _configuration.Get<T>();
else
return _configuration.GetSection(key).Get<T>();
}
public static T GetObject<T>(string key = null)
{
if (string.IsNullOrWhiteSpace(key))
return Instance._configuration.Get<T>();
else
{
var section = Instance._configuration.GetSection(key);
return section.Get<T>();
}
}
public static T GetObject<T>(string key, T defaultValue)
{
if (Instance._configuration.GetSection(key) == null)
return defaultValue;
if (string.IsNullOrWhiteSpace(key))
return Instance._configuration.Get<T>();
else
return Instance._configuration.GetSection(key).Get<T>();
}
}
}
步骤2。AppSettings对象的初始配置
我们需要声明和加载appsettings。json文件,加载AppSettings对象的配置信息。我们将在Startup.cs文件的构造函数中完成这项工作。
请注意行AppSettings.Instance.SetConfiguration(配置);
public Startup(IHostingEnvironment evm)
{
var builder = new ConfigurationBuilder()
.SetBasePath(evm.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{evm.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build(); // load all file config to Configuration property
AppSettings.Instance.SetConfiguration(Configuration);
}
现在我有了appsettings。Json文件与一些关键字如下:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ConnectionString": "Data Source=localhost;Initial Catalog=ReadConfig;Persist Security Info=True;User ID=sa;Password=12345;"
},
"MailConfig": {
"Servers": {
"MailGun": {
"Pass": "65-1B-C9-B9-27-00",
"Port": "587",
"Host": "smtp.gmail.com"
}
},
"Sender": {
"Email": "example@gmail.com",
"Pass": "123456"
}
}
}
步骤3。从操作中读取配置值
我在Home控制器中演示一个动作,如下所示:
public class HomeController : Controller
{
public IActionResult Index()
{
var connectionString = AppSettings.Instance.GetConnection("ConnectionString");
var emailSender = AppSettings.Instance.Get<string>("MailConfig:Sender:Email");
var emailHost = AppSettings.Instance.Get<string>("MailConfig:Servers:MailGun:Host");
string returnText = " 1. Connection String \n";
returnText += " " +connectionString;
returnText += "\n 2. Email info";
returnText += "\n Sender : " + emailSender;
returnText += "\n Host : " + emailHost;
return Content(returnText);
}
}
结果如下:
点击查看结果