Record a little every day: NetCore gets the configuration file appsettings.json

Using NetCore for projects

Due to other ORMs used by many friends, such as SqlSugar, NH, Dapper, etc., when reading the connection string, the information is often saved in a configuration file, such as appsetting.json,

There is a lot of information about reading appsetting.json on the Internet through injection. When ORM reads the configuration, it is all in a class library, so the injection method is sometimes not suitable for [personal understanding]

 

Because of the above scenario, the following method to read the configuration can be used anywhere

 

Friends who like NetCore, welcome to join the group QQ: 86594082

Source code to be added later

 

1. In the project, create a new NetCore class library and create the class ConfigServices

namespace Core.Extensions
{
    ///  <summary> 
    /// Read the configuration file
     ///  </summary> 
    public  class ConfigServices
    {
        public static IConfiguration Configuration { get; set; }
        static ConfigServices()
        {
            // ReloadOnChange = true Reload             
            Configuration = new ConfigurationBuilder() when appsettings.json is modified
            .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
            .Build();
        }
    }
}

2. Add custom configuration in appsettings.json under the web project

{
  "DBConnection": {
    "MySqlConnectionString": "server=localhost;database=fyt_ims;uid=root;pwd=123456;charset='utf8';SslMode=None"
  },  
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

 

3. Create a new class that reads the configuration

namespace FytErp.Core.Model.ConfigModel
{
    /// <summary>
    /// Database connection string
    /// </summary>
    public class DBConnection
    {
        /// <summary>
        /// MySql database connection string
        /// </summary>
        public string MySqlConnectionString { get; set; }

        /// <summary>
        /// SqlServer database connection string
        /// </summary>
        public string SqlServerConnectionString { get; set; }
    }
}

 

4. Write a test to read the configuration

namespace FytErp.Web.Pages
{
    public class IndexModel : PageModel
    {
        public DbConnection DbSetting { get; private set; }
        public void OnGet()
        {
            // Get the DBConnection node in the configuration file 
            DbSetting = ConfigServices.Configuration.GetSection( " DbConnection " ).Get<DbConnection> ();
        }
    }
}

 

5. Final read result

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324646917&siteId=291194637