.NET Core Get custom profile information

Foreword

  .net core oncoming unstoppable. Now that fail to do so, then we will comply with it. Understand it and learn it. Today we take a look at the similarities and differences before and .net version of the configuration file read mode, not repeat them here .NET Core basics.

ps: update, update a variety of ways to read profile information, in conjunction with their actual situation Tell me what you choose the right way to read .

Implementation of a

Json file we first look at the original is like:

 
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "Test": {
    "One": 123,
    "Two": "456",
    "Three": "789",
    "Content": {
      "cone": 111,
      "ctwo": "潇十一郎" 
    } 
  }
}
 

 Json read profile information, we need to installMicrosoft.Extensions.Configuration.Json 包,如下:

 

Then add Json call AddJsonFile configured to ConfigurationBuilder the Provider, to achieve the following:

We will change the Configuration Properties

public static IConfiguration Configuration { get; set; }

Then ConfigureServices  will be added to the Provider Json arranged in ConfigurationBuilder

 var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");
            Configuration = builder.Build();
            services.AddSingleton<IConfiguration>(Configuration);//配置IConfiguration的依赖

Then you have configured, we can read, of course, if it is called in other places, we need to inject through Constructor IConfiguration

A read mode: use key to read as follows:

 

 
        Readonly IConfiguration _configuration Private; 
        // configured injection 
        public the HomeController (IConfiguration Configuration) 
        { 
            _configuration = Configuration; 
        } 

        public IActionResult Index () 
        { 
            // Key value obtained by way of a 
            var one = _configuration [ "Test: One"]; // 123 
            var conw = _configuration [ "Test: Content: ctwo"]; // Xiao Juichiro 
        }
 

 

Reading two ways: use GetValue<T>, to install Microsoft.Extensions.Configuration.Binderthe package, reads as follows:

 
        Readonly IConfiguration _configuration Private; 
        // configured injection 
        public the HomeController (IConfiguration Configuration) 
        { 
            _configuration = Configuration; 
        } 

        public IActionResult Index () 
        { 

            // Second way <T> (string key) GetValue first embodiment is obtained by direct access of the key If you can not find two specify default values 
            var TWO = _configuration.GetValue <int> ( "the Test: One"); // 123 
            var = _configuration.GetValue Three <String> ( "the Test: Three"); // 789 
            var ctwo = _configuration.GetValue <string> ( "Test: Content: ctwo"); // Xiao Shiyi Lang 

            var four = _configuration.GetValue <string> ( "Test: four", " I am a default value");// I am a default value 

        }
 

Special instructions: generic GetValue form has two overloaded, it is a GetValue ( "key"), the other is a default value specified GetValue ( "key", defaultValue) configuration if the key is not present, first. kind of result is default (T), the second result is specified default value.

Both read mode debugger is as follows:

 

 

Implementation of the two

Note: You need NuGet introduced: Microsoft.Extensions.Options.ConfigurationExtensions

① We then profile appsettings.json in new custom API Json as follows:

 
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "API": {
    "Url": "http://localhost:8080/",
    "getclub": "api/club"
  } 
}
 

② Then we define a static class, and then declare a class type variable IConfigurationSection

private static IConfigurationSection _appSection = null;

③ Write a static method AppSetting Value item acquired configuration, as follows:

 
       public static string AppSetting(string key)
        {
            string str = string.Empty;
            if (_appSection.GetSection(key) != null)
            {
                str = _appSection.GetSection(key).Value;
            }
            return str;
        }
 

④ IConfigurationSection need to set initial values ​​as follows:

       public static void SetAppSetting(IConfigurationSection section)
        {
            _appSection = section;
        }

⑤ then write a corresponding value can be read depending Json items:

  public static string GetSite(string apiName)
  {
      return AppSetting(apiName);
  }

⑥ With the above steps, basically read the code have all been finished, the last remaining one of the most important steps, Json configuration file to be read to Configure method Startup.cs in, as follows:

In this way, we can easily get to the configuration items we want, and the whole CS code is as follows:

 
    /// <summary>
    /// 配置信息读取模型
    /// </summary>
    public static class SiteConfig
    {
        private static IConfigurationSection _appSection = null;

        /// <summary>
        /// API域名地址
        /// </summary>
        public static string AppSetting(string key)
        {
            string str = string.Empty;
            if (_appSection.GetSection(key) != null)
            {
                str = _appSection.GetSection(key).Value;
            }
            return str;
        }

        public static void SetAppSetting(IConfigurationSection section)
        {
            _appSection = section;
        }

        public static string GetSite(string apiName)
        {
            return AppSetting(apiName);
        }
    }
 

最后 ,我们来跑一下演示效果如下:

1|0 补充

 

事务总是不断发展,有更优的做法,那就一定要摒弃以前不太美的实现,现在补充一种实现获取配置文件的方法,更为优雅美观:

 NuGet引入:Microsoft.Extensions.Configuration 包

在appsetting中加入短信相关配置信息:

 

在Startup.cs中重写:

 
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }
 

新建一个静态类:ConfigurationKeys

 
public class ConfigurationKeys
{
        public static string SMS_APP_URL = "sms:url";

        public static string SMS_APP_ID = "sms:appid";

        public static string SMS_APP_SECRET = "sms:secret";

        public static string SMS_VERIFY_CODE_TEMPLATE = "sms:verifycodetemplate";
}
 

1|1使用

 

在具体的控制器或者类中注入:

private readonly IConfiguration _config;
public SmsServices(IConfiguration config)
{
    _config = config;
}
var templateId = _config[ConfigurationKeys.SMS_VERIFY_CODE_TEMPLATE];

    完!

 

Guess you like

Origin www.cnblogs.com/webenh/p/11598873.html