Asp.Net Core reads the appsettings.json configuration file

Keywords: JSON

 How does Asp.Net Core read the appsettings.json configuration file? Recently, I also learned how to read configuration files.
 It is mainly accomplished through IConfiguration and initialization in Program. So today I'll show you how to read the configuration file.

First, create a public class GetAppset that reads the configuration file. We can see what's in the configuration file at this point.

{
  "GetSetting": {
    "option1": "value1_from_json",
    "option2": -1,
    "subsection": {
      "suboption1": "subvalue1_from_json",
      "suboption2": 200
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Write the following code in the created GetAppsetting public class

  /// <summary>
        /// Instantiate and call GetAppset ()
        /// </summary>
        /// <param name="builder"></param>
        public static void connection(IConfiguration build)
        {
            getvalue = new GetAppsetting(build);
        }
 
        /// <summary>
        /// Connecting in a class
        /// </summary>
        public static GetAppsetting getvalue { get; private set; }
 
        /// <summary>
        /// The final instantiation of GetAppset (configuration file) reads the configuration under GetSetting
        /// </summary>
        /// <param name="builder"></param>
        public GetAppsetting(IConfigurationbuild)
        {
            this.GetSettings = new GetSetting(build.GetSection("GetSetting"));
        }  
 
        public  GetSetting GetSettings { get; }
        /// <summary>
        /// Get the values of the specific properties below the configuration
        /// </summary>
        public class GetSetting
        {
            public string option1 { get; }
            public GetSetting(IConfiguration Configuration)
            {
                this.option1 = Configuration.GetSection("option1").Value;
            }
        }

Finally, it needs to be initialized in the Main function in Program

var Configuration = new ConfigurationBuilder()
             .Add(new JsonConfigurationSource { Path = "appsettings.json",  ReloadOnChange = true })
             .Build();
            GetAppsetting.connection(Configuration);


var a = GetAppsetting.getvalue.GetSettings.option1;//So we can get the property value of option 1 under GetSetting in the configuration file.

Reference resources: https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2

Posted by norbie on Sat, 13 Apr 2019 10:51:32 -0700