這篇文章將為大家詳細講解有關.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" } }
②然后我們定義一個靜態(tài)類,再類中申明一個IConfigurationSection 類型變量
private static IConfigurationSection _appSection = null;
③寫一個AppSetting靜態(tài)方法獲取到配置的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); } }
最后 ,我們來跑一下演示效果如下:
關于“.NET Core2.1怎么獲取自定義配置文件信息”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
本文標題:.NETCore2.1怎么獲取自定義配置文件信息-創(chuàng)新互聯
轉載注明:http://jinyejixie.com/article10/dphodo.html
成都網站建設公司_創(chuàng)新互聯,為您提供虛擬主機、關鍵詞優(yōu)化、全網營銷推廣、品牌網站制作、網站建設、建站公司
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯