Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
{ "ConnectionStrings": { "dbName": "server=localhost;database=hr;PORT=3306;uid=root;pwd=123456;charset=gb2312" }, "AppSettings": { "Url": "12" } }
特别注意:
using Microsoft.Extensions.Configuration; using System; using System.IO; namespace CustomAttributes.Model { public class Appsettings { private IConfigurationRoot Configuration; private Appsettings() { var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json"); Configuration = builder.Build(); } private static readonly Lazy<Appsettings> InstanceLock = new Lazy<Appsettings>(() => new Appsettings() { }); public static Appsettings Instance { get { return InstanceLock.Value; } } public string GetByKey(string key) { return Configuration.GetSection(key).Value; } public string GetConnectionString() { return Configuration.GetConnectionString("dbName"); } } }
using CustomAttributes.Model; using System; namespace CustomAttributesApp { class Program { static void Main(string[] args) { Console.WriteLine(Appsettings.Instance.GetByKey("AppSettings:Url")); Console.WriteLine(Appsettings.Instance.GetConnectionString()); } } }
.net 5.0 - 控制台加载appsettings.json文件
原文:https://www.cnblogs.com/gygtech/p/14762431.html