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

简介: 前言   .net core来势已不可阻挡。既然挡不了,那我们就顺应它。了解它并学习它。今天我们就来看看和之前.net版本的配置文件读取方式有何异同,这里不在赘述.NET Core 基础知识。 ps:更新版,更新了多种方式实现读取配置文件信息,各位看官结合自己实际情况选择合适的读取方式即可。

前言

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

ps:更新版,更新了多种方式实现读取配置文件信息,各位看官结合自己实际情况选择合适的读取方式即可

实现方式一

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

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

 读取Json配置文件信息,我们需要安装Microsoft.Extensions.Configuration.Json 包,如下:

 

然后再 调用AddJsonFile把Json配置的Provider添加到ConfigurationBuilder中,实现如下:

我们将Configuration 属性改成

public static IConfiguration Configuration { get; set; }

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

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

然后配置完,我们就可以读取了,当然,如果是在其他地方调用,就需要通过构造函数注入IConfiguration

读取方式一:使用key读取,如下:

 

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

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

  • 感谢你的阅读。如果你觉得这篇文章对你有帮助或者有启发,就请推荐一下吧~你的精神支持是博主强大的写作动力。欢迎转载!
  • 博主的文章没有高度、深度和广度,只是凑字数。由于博主的水平不高(其实是个菜B),不足和错误之处在所难免,希望大家能够批评指出。
  • 欢迎加入.NET 从入门到精通技术讨论群→523490820 期待你的加入
  • 不舍得打乱,就永远学不会复原。被人嘲笑的梦想,才更有实现的价值。
  • 我的博客:http://www.cnblogs.com/zhangxiaoyong/
目录
相关文章
|
14天前
.NET 压缩/解压文件
【9月更文挑战第5天】在 .NET 中,可利用 `System.IO.Compression` 命名空间进行文件的压缩与解压。首先引入相关命名空间,然后通过 GZipStream 类实现具体的压缩或解压功能。下面提供了压缩与解压文件的方法示例及调用方式,便于用户快速上手操作。
|
26天前
|
API
【Azure Key Vault】.NET 代码如何访问中国区的Key Vault中的机密信息(Get/Set Secret)
【Azure Key Vault】.NET 代码如何访问中国区的Key Vault中的机密信息(Get/Set Secret)
|
29天前
|
Java Windows 容器
【应用服务 App Service】快速获取DUMP文件(App Service for Windows(.NET/.NET Core))
【应用服务 App Service】快速获取DUMP文件(App Service for Windows(.NET/.NET Core))
|
27天前
|
开发框架 .NET Docker
【Azure 应用服务】App Service .NET Core项目在Program.cs中自定义添加的logger.LogInformation,部署到App Service上后日志不显示Log Stream中的问题
【Azure 应用服务】App Service .NET Core项目在Program.cs中自定义添加的logger.LogInformation,部署到App Service上后日志不显示Log Stream中的问题
|
27天前
|
开发框架 .NET Linux
【Azure Developer】已发布好的.NET Core项目文件如何打包为Docker镜像文件
【Azure Developer】已发布好的.NET Core项目文件如何打包为Docker镜像文件
|
1月前
|
人工智能 文字识别
通义语音AI技术问题之LCB-net模型对幻灯片中文本信息的使用如何解决
通义语音AI技术问题之LCB-net模型对幻灯片中文本信息的使用如何解决
13 0
|
2月前
|
存储 对象存储 Python
`openpyxl`是一个用于读写Excel 2010 xlsx/xlsm/xltx/xltm文件的Python库。它不需要Microsoft Excel,也不需要.NET或COM组件。
`openpyxl`是一个用于读写Excel 2010 xlsx/xlsm/xltx/xltm文件的Python库。它不需要Microsoft Excel,也不需要.NET或COM组件。
|
2月前
|
算法 API 数据安全/隐私保护
.NET使用原生方法实现文件压缩和解压
.NET使用原生方法实现文件压缩和解压
.NET使用原生方法实现文件压缩和解压
|
2月前
|
存储 C#
.NET使用CsvHelper快速读取和写入CSV文件
.NET使用CsvHelper快速读取和写入CSV文件
|
3月前
|
安全 程序员 Shell
老程序员分享:NSIS自定义界面,下载并安装Net.Framework4.8
老程序员分享:NSIS自定义界面,下载并安装Net.Framework4.8