1、安装所有NuGet包

2、上代码
2.1 新建helper类
| private static IConfiguration _config; |
| |
| public AppsettingHelper(IConfiguration configuration) |
| { |
| _config = configuration; |
| } |
| |
| |
| |
| |
| |
| |
| |
| public static string Get(string key, bool IsConn = false) |
| { |
| string value = null; |
| try |
| { |
| if (string.IsNullOrWhiteSpace(key)) |
| { |
| return null; |
| } |
| |
| var Configuration = new ConfigurationBuilder() |
| .SetBasePath(System.IO.Directory.GetCurrentDirectory()) |
| .AddJsonFile("appsettings.json") |
| .AddJsonFile("appsettings.test.json", true, reloadOnChange: true); |
| |
| var config = Configuration.Build(); |
| if (IsConn) |
| value = config.GetConnectionString(key); |
| else |
| value = config[key]; |
| } |
| catch (Exception ex) |
| { |
| value = null; |
| } |
| return value; |
| } |
| |
| |
| |
| |
| |
| |
| |
| public static List<T> Get<T>(params string[] session) |
| { |
| List<T> list = new List<T>(); |
| _config.Bind(string.Join(":", session), list); |
| return list; |
| } |
2.2 Program.cs注入服务
| IConfiguration configuration = new ConfigurationBuilder() |
| .AddJsonFile("appsettings.json") |
| .Build(); |
| builder.Services.AddSingleton(new Y.WebAPI.Utility.AppsettingHelper(configuration)); |
2.3 定义配置文件节点类
| public class RabbitMQConfig |
| { |
| public string HostName { set; get; } |
| public string Port { set; get; } |
| public string UserName { set; get; } |
| public string Password { set; get; } |
| public List<string> QueueName { set; get; } |
| } |
2.4 使用
| List<RabbitMQConfig> rabbitMQs = AppsettingHelper.Get<RabbitMQConfig>("RabbitMQ"); |
3、appsettings.json文件
| { |
| "Logging": { |
| "LogLevel": { |
| "Default": "Information", |
| "Microsoft.AspNetCore": "Warning" |
| } |
| }, |
| "AllowedHosts": "*", |
| "RabbitMQ": [ |
| { |
| "HostName": "192.168.1.1", |
| "Port": "0000", |
| "UserName": "user1", |
| "Password": "111111", |
| "QueueName": [ "Y.Queue1"] |
| } |
| ] |
| } |
参考:https://blog.csdn.net/runliuv/article/details/122484173
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!