基于VS2019,使用步骤:
方式一:
第一步:appsettings.json 定义配置项,可理解为定义对象属性,eg:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | { "Logging" : { "LogLevel" : { "Default" : "Information" , "Microsoft" : "Warning" , "Microsoft.Hosting.Lifetime" : "Information" } }, "MEASSettings" : { "PrintName" : "wula" , "PrintNum" : 12 }, "AllowedHosts" : "*" } |
第二步:定义实体对象,eg:
1 2 3 4 5 6 7 8 9 10 11 | using System; namespace Test { public class MEASSettings { public string PrintName { get ; set ; } public string PrintNum { get ; set ; } } } |
第三步:读取配置项公共方法提取,创建DLL(基于.NET 5.0略)
注:需安装如下依赖项,略
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; using System; namespace MEAS.Common { public class AppsettingsHelper { public IConfiguration Configuration { get ; set ; } //定义一个用于保存静态变量的实例 private static AppsettingsHelper instance = null ; //定义一个保证线程同步的标识 private static readonly object locker = new object (); //构造函数为私有,使外界不能创建该类的实例 private AppsettingsHelper() { Configuration = new ConfigurationBuilder() .Add( new JsonConfigurationSource { Path = "appsettings.json" , ReloadOnChange = true }) .Build(); } public static AppsettingsHelper Instance { get { if (instance == null ) { lock (locker) { if (instance == null ) instance = new AppsettingsHelper(); } } return instance; } } /// <summary> /// 根据索引获取配置项value值 /// </summary> /// <param name="indexPath"></param> /// <returns></returns> public string GetConfigByIndex( string indexPath) { return Configuration[indexPath].ToString(); //Configuration["MEASSettings:PrintName"]; } /// <summary> /// 根据节点获取配置文件对象实例 /// </summary> /// <param name="className"></param> /// <returns></returns> public IConfiguration GetConfigObjs( string className) { //string aa = Configuration.GetSection("MEASSettings").Get<MEASSettings>().PrintName; return Configuration.GetSection(className); // MEASSettings bbbb = see.Get<MEASSettings>(); } /// <summary> /// 根据具体对象获取对象实例 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="obj">实体对象</param> /// <returns></returns> public object GetConfigObjByEntity<T>(T obj) { string className = Type.GetType(obj.ToString()).Name; return Configuration.GetSection(className).Get(Type.GetType(obj.ToString())); } } } |
第五步:使用方式如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 | //方式一 string aa = Configuration.GetSection( "MEASSettings" ).Get<MEASSettings>().PrintName; MEASSettings aaa = Configuration.GetSection( "MEASSettings" ).Get<MEASSettings>(); //方式二 string bb = ConfigHelper.Instance.GetConfigByIndex( "MEASSettings:PrintName" ); //方式三 IConfiguration cc = ConfigHelper.Instance.GetConfigObjs( "MEASSettings" ); MEASSettings ccc = cc.Get<MEASSettings>(); //方式四 MEASSettings set = new MEASSettings(); MEASSettings ddd = ConfigHelper.Instance.GetConfigObjByEntity<MEASSettings>( set ) as MEASSettings; //方式五 MEASSettings temp = ConfigHelper.Instance.GetConfigObjByEntity<MEASSettings>( new MEASSettings()) as MEASSettings; |
方式二:
第一步,根据appsettings.json 文件创建对应的对象模型
注:选择对应的对象(选择单个对象时,只选择对应的中括号)==》下面是选择所有配置内容后自动生成对象模型
自动生成后需根据实际情况修改对应的实体类名称--修改名称略
对象如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | { "Logging" : { "LogLevel" : { "Default" : "Information" , "Microsoft" : "Warning" , "Microsoft.Hosting.Lifetime" : "Information" } }, "MEASSettings" : { "PrintName" : "wula" , "PrintNum" : 12 }, "AllowedHosts" : "*" } //对应实体如下所示: using System; namespace Test { public class AppSettings { public Logging Logging { get ; set ; } public MEASSettings MEASSettings { get ; set ; } public string AllowedHosts { get ; set ; } } public class Logging { public Loglevel LogLevel { get ; set ; } } public class Loglevel { public string Default { get ; set ; } public string Microsoft { get ; set ; } public string MicrosoftHostingLifetime { get ; set ; } } public class MEASSettings { public string PrintName { get ; set ; } public int PrintNum { get ; set ; } } } |
第二步:根据视图对象模型,通过IConfiguration获取整个对象模型的对象
//通过对象模型获取AppSettings对象集合
var setting = new AppSettings();
Configuration.Bind(setting);
//调用使用AppSettings对象属性
string printName=setting.MEASSettings.PrintName;
//部分绑定
var measSettings = new MEASSettings();
Configuration.GetSection("measSettings").Bind(measSettings);
方式三:注册配置选项服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public void ConfigureServices(IServiceCollection services) { //注册配置选项服务 services.Configure<AppSettings>(Configuration); //...... } public void Configure(IApplicationBuilder app, IWebHostEnvironment env,IOptions<AppSettings> options) {<br> //使用配置选项服务 string printName = options.Value.MEASSettings.PrintName; if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint( "/swagger/v1/swagger.json" , "WebApplication1 v1" )); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } |
方式四:
//自定义读取配置文件 + 注册配置选项服务
//自定义配置,注册配置选项,读取时通过options方式读取
var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
string printName2=config["MEASSettings:PrintName"];
services.Configure<AppSettings>(config);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本