• C# .NET5.0 读取appsettings.json


    基于VS2019,使用步骤:

    方式一:

    第一步:appsettings.json 定义配置项,可理解为定义对象属性,eg:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "MEASSettings": 
      {
        "PrintName": "wula",
        "PrintNum": 12
      },
    
      "AllowedHosts": "*"
    
    }
    

    第二步:定义实体对象,eg:

    using System;
    
    namespace Test
    {
        public class MEASSettings
        {
            public string PrintName { get; set; }
            public string PrintNum { get; set; }
    
        }
    } 

     第三步:读取配置项公共方法提取,创建DLL(基于.NET 5.0略)

    注:需安装如下依赖项,略

    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()));
            }
    
        }
    }
    

    第五步:使用方式如下所示:

                //方式一
                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 文件创建对应的对象模型

    注:选择对应的对象(选择单个对象时,只选择对应的中括号)==》下面是选择所有配置内容后自动生成对象模型

    自动生成后需根据实际情况修改对应的实体类名称--修改名称略

    对象如下所示:

    {
      "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);

    方式三:注册配置选项服务

      public void ConfigureServices(IServiceCollection services)
            {
                //注册配置选项服务
                services.Configure<AppSettings>(Configuration);
                //......
           }  
    
     public void Configure(IApplicationBuilder app, IWebHostEnvironment env,IOptions<AppSettings> options)
            {
            //使用配置选项服务 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);

      

    博客内容主要用于日常学习记录,内容比较随意,如有问题,还需谅解!!!
  • 相关阅读:
    【Leetcode_easy】1030. Matrix Cells in Distance Order
    【Leetcode_easy】1033. Moving Stones Until Consecutive
    【Leetcode_easy】1037. Valid Boomerang
    【Leetcode_easy】1042. Flower Planting With No Adjacent
    【Leetcode_easy】1046. Last Stone Weight
    【Leetcode_easy】1047. Remove All Adjacent Duplicates In String
    【Leetcode_easy】1051. Height Checker
    【Leetcode_easy】1071. Greatest Common Divisor of Strings
    【Leetcode_easy】1154. Day of the Year
    【Leetcode_easy】1170. Compare Strings by Frequency of the Smallest Character
  • 原文地址:https://www.cnblogs.com/YYkun/p/15570848.html
Copyright © 2020-2023  润新知