需要用到的包:
Microsoft.Extensions.Configuration.Json
:负责加载 JSON 配置文件,解析其中的内容。
Microsoft.Extensions.Configuration.Binder
:负责将解析的配置数据绑定到实体
public class AppSettings { public static IConfiguration Configuration { get; set; } public AppSettings(IConfiguration configuration) { Configuration = configuration; } public AppSettings(string basePath) { string path = "appsettings.json"; Configuration = new ConfigurationBuilder() .SetBasePath(basePath) .Add(new JsonConfigurationSource { Path = path, Optional = false, ReloadOnChange = true }) .Build(); } public static string AppString(params string[] paras) { if (paras.Length != 0) { return Configuration[string.Join(":", paras)]; } return string.Empty; } public static T AppEntity<T>(params string[] paras) { return Configuration.GetSection(string.Join(":", paras)).Get<T>(); } public static List<T> AppEntitys<T>(params string[] paras) { return Configuration.GetSection(string.Join(":", paras)).Get<List<T>>(); } public static List<KeyValuePair<string, string>> AppKeys(params string[] paras) { return Configuration.GetSection(string.Join(":", paras)) .GetChildren().Select(x => new KeyValuePair<string, string>(x.Key, x.Value)).ToList(); } }
注入:program.cs里面
builder.Services.AddSingleton(new AppSettings(builder.Configuration));
使用:
AppSettings.AppString("AppConfig:ApiName");
标签:封装,string,配置文件,AppSettings,paras,访问,static,Configuration,public From: https://www.cnblogs.com/zhang-3/p/18663840