亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

.NET Core2.1獲取自定義配置文件信息

標簽:
C#

前言

  .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方法中,如下:

https://img1.sycdn.imooc.com//5b665e810001e2ee06040354.jpg

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

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

https://img1.sycdn.imooc.com//5b665e900001b8a602240025.jpg

原文出处:https://www.cnblogs.com/zhangxiaoyong/p/9411036.html

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消