.net core 读取appsetting.json(一):Appsettings帮助类取值方法
创建类Appsettings.cs
/// <summary> /// appsettings.json操作类 /// </summary> public class Appsettings { static IConfiguration Configuration { get; set; } static string contentPath { get; set; } public Appsettings(string contentPath) { string Path = "appsettings.json"; //如果你把配置文件 是 根据环境变量来分开了,可以这样写 //Path = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json"; Configuration = new ConfigurationBuilder() .SetBasePath(contentPath) .Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true })//这样的话,可以直接读目录里的json文件,而不是 bin 文件夹下的,所以不用修改复制属性 .Build(); } /// <summary> /// 封装要操作的字符 /// </summary> /// <param name="sections">节点配置</param> /// <returns></returns> public static string app(params string[] sections) { try { if (sections.Any()) { return Configuration[string.Join(":", sections)]; } } catch (Exception) { } return ""; } }
依赖注入IWebHostEnvironment 用来用去路径
public IConfiguration Configuration { get; } public IWebHostEnvironment Env { get; } public Startup(IConfiguration configuration, IWebHostEnvironment env) { Configuration = configuration; Env = env; }
注册Appsettings
services.AddSingleton(new Appsettings(Env.ContentRootPath));
appsetting.json如下
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "Qny": { "qiniuyunAK": "AK", //ak "qiniuyunSK": "SK", //sk "qiniuyunBucket": "空间名称", "prefixPath": "http://www.baidu.com" } }
使用取值
Appsettings.app(new string[] { "Qny", "qiniuyunAK" });//AK Appsettings.app(new string[] { "Qny", "qiniuyunSK" });//SK Appsettings.app(new string[] { "Qny", "qiniuyunBucket" });//空间名称 Appsettings.app(new string[] { "Qny", "prefixPath" }); //http://www.baidu.com