首页 技术 正文
技术 2022年11月14日
0 收藏 992 点赞 2,916 浏览 3805 个字

前言

.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 包,如下:

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

然后再 调用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),第二种结果为指定的默认值.

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

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

实现方式二

注:需要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方法中,如下:

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

这样,我们就可以很轻松的获取到我们想要的配置项了,整段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);
}
}

 

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

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

1|0 补充

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

NuGet引入:Microsoft.Extensions.Configuration 包

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

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

在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];

完!

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,030
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,859