服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - ASP.NET教程 - .NET Core2.1如何获取自定义配置文件信息详解

.NET Core2.1如何获取自定义配置文件信息详解

2020-05-31 14:24潇十一郎 ASP.NET教程

这篇文章主要给大家介绍了关于.NET Core2.1如何获取自定义配置文件信息的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

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

实现

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
{
 "Logging": {
 "IncludeScopes": false,
 "LogLevel": {
  "Default": "Warning"
 }
 },
 "API": {
 "Url": "http://localhost:8080/",
 "getclub": "api/club"
 }
}

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

?
1
private static IConfigurationSection _appSection = null;

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

?
1
2
3
4
5
6
7
8
9
public static string AppSetting(string key)
{
 string str = string.Empty;
 if (_appSection.GetSection(key) != null)
 {
  str = _appSection.GetSection(key).Value;
 }
 return str;
}

④需要设置IConfigurationSection初始值,如下:

?
1
2
3
4
public static void SetAppSetting(IConfigurationSection section)
{
 _appSection = section;
}

⑤然后写一个根据不同Json项读取出对应的值即可:

?
1
2
3
4
public static string GetSite(string apiName)
{
 return AppSetting(apiName);
}

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

.NET Core2.1如何获取自定义配置文件信息详解

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/// <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 Core2.1如何获取自定义配置文件信息详解

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:https://www.cnblogs.com/zhangxiaoyong/p/9411036.html

延伸 · 阅读

精彩推荐