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

发布时间:2021-02-08 10:29:42 作者:小新
来源:亿速云 阅读:137

这篇文章将为大家详细讲解有关.NET Core2.1怎么获取自定义配置文件信息,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

前言

.net core来势已不可阻挡。既然挡不了,那我们就顺应它。了解它并学习它。今天我们就来看看和之前.net版本的配置文件读取方式有何异同,这里不在赘述.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 Core2.1怎么获取自定义配置文件信息

这样,我们就可以很轻松的获取到我们想要的配置项了,整段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 Core2.1怎么获取自定义配置文件信息

关于“.NET Core2.1怎么获取自定义配置文件信息”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. NET Core 3.0 AutoFac内置DI替换的示例分析
  2. 如何在.Net项目中配置NLog

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

core2.1

上一篇:Linux下查杀stopped进程的方法

下一篇:在vue项目中使用eslint+prettier格式化代码的示例

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》