参考https://blog.csdn.net/yenange/article/details/82457761
http://www.mamicode.com/info-detail-2602438.html
private static string GetCustomSettings(string key)
{
var config = new ConfigurationBuilder()
.AddInMemoryCollection()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
return config.GetSection("CustomSettings").GetValue(key, string.Empty);
}
// 获取自定义value
public static string WXWarningClosedTemplateID => GetCustomSettings("xxx");
二
using Microsoft.Extensions.Configuration;
using System;
namespace ConsoleApp4
{
class Program
{
//安装 .net core 2.1 完整包
//install-package Microsoft.AspNetCore.All -version 2.1.0
//注意不要超过 依赖项->SDK->Microsoft.NETCore.App 的版本,我这里是 2.1.0
//否则会无法正常生成和运行
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
Console.WriteLine($"ServerCode:{configuration["ServerCode"]}");
UserInfo user1 = new UserInfo();
UserInfo user2 = new UserInfo();
configuration.GetSection("section0").Bind(user1);
configuration.GetSection("section1").Bind(user2);
Console.WriteLine(user1.ToString());
Console.WriteLine(user2.ToString());
Console.WriteLine($"section0:UserId:{configuration["section0:UserId"]}");
Console.Read();
}
}
public class UserInfo
{
public long UserId { get; set; }
public string UserName { get; set; }
public override string ToString()
{
return string.Format($"UserId:{UserId}, UserName:{UserName}");
}
}
}
网友评论