.NET Core 获取自定义配置文件信息

前言

  .net core来势已不可阻挡。既然挡不了,那咱们就顺应它。了解它并学习它。今天咱们就来看看和以前.net版本的配置文件读取方式有何异同,这里不在赘述.NET Core 基础知识。json

ps:更新版,更新了多种方式实现读取配置文件信息,各位看官结合本身实际状况选择合适的读取方式便可api

实现方式一

咱们先来看下初始的Json文件是怎样的:app

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

 读取Json配置文件信息,咱们须要安装Microsoft.Extensions.Configuration.Json 包,以下:ide

 

而后再 调用AddJsonFile把Json配置的Provider添加到ConfigurationBuilder中,实现以下:函数

咱们将Configuration 属性改为学习

public static IConfiguration Configuration { get; set; }ui

而后再ConfigureServices 中将Json配置的Provider添加到ConfigurationBuilder中url

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

而后配置完,咱们就能够读取了,固然,若是是在其余地方调用,就须要经过构造函数注入IConfiguration spa

读取方式一:使用key读取,以下:.net

 

        private readonly IConfiguration _configuration;
        //构造注入
        public HomeController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public IActionResult Index()
        {
            //方式一 经过 Key值获取
            var one = _configuration["Test:One"]; //123
            var conw = _configuration["Test:Content:ctwo"]; //潇十一郎
        }

 

读取方式二:使用GetValue<T>,须要安装Microsoft.Extensions.Configuration.Binder包,读取以下:

        private readonly IConfiguration _configuration;
        //构造注入
        public HomeController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public IActionResult Index()
        {

            //方式二 经过GetValue<T>(string key)方式获取 第一个是直接获取key 第二个若查找不到则指定默认值
            var two = _configuration.GetValue<int>("Test:One"); //123
            var three = _configuration.GetValue<string>("Test:Three"); //789
            var ctwo = _configuration.GetValue<string>("Test:Content:ctwo"); //潇十一郎

            var four = _configuration.GetValue<string>("Test:four", "我是默认值"); //我是默认值

        }

特别说明一下:GetValue的泛型形式有两个重载,一个是GetValue("key"),另外一个是能够指定默认值的GetValue("key",defaultValue).若是key的配置不存在,第一种结果为default(T),第二种结果为指定的默认值.

上述两个读取方式调试图以下:

 

 

实现方式二

注:须要NuGet引入:Microsoft.Extensions.Options.ConfigurationExtensions

①咱们再配置文件appsettings.json中 新增自定义API Json以下:

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

②而后咱们定义一个静态类,再类中申明一个IConfigurationSection 类型变量

private static IConfigurationSection _appSection = null;

③写一个AppSetting静态方法获取到配置的Value项,代码以下:

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

④须要设置IConfigurationSection初始值,以下:

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

⑤而后写一个根据不一样Json项读取出对应的值便可:

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

⑥有了以上几个步骤,基本上读取代码已经所有写完,剩下最后一个最重要的步骤,将要读取的Json文件配置到Startup.cs的Configure方法中,以下:

这样,咱们就能够很轻松的获取到咱们想要的配置项了,整段CS代码以下:

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

最后 ,咱们来跑一下演示效果以下:

 补充

事务老是不断发展,有更优的作法,那就必定要摒弃之前不太美的实现,如今补充一种实现获取配置文件的方法,更为优雅美观:

 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";
}

使用

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

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

    完!

相关文章
相关标签/搜索