.NET?Core讀取配置文件的方法
配置文件是每個項目最基礎(chǔ)的部分,也是不可或缺的部分,比如:數(shù)據(jù)庫連接、中間件屬性等常見的配置。
今天這篇文章主要內(nèi)容就是,在.Net Core項目中怎樣去讀取配置文件并使用。
提前準(zhǔn)備
appsettings.json 文件
{ "User": { "userName": "趙一", "userAge": 18 } }
對應(yīng)實體模型
public class UserOption { public string userName { get; set; } public int userAge { get; set; } }
常規(guī)讀取
1、注冊
在 startup 類中注冊,主要用到的是 Configure 方法:
services.Configure<UserOption>(Configuration.GetSection("User"));
2、控制器中注入并讀取
public class HomeController : ControllerBase { private readonly UserOption user; public HomeController(IOptions<UserOption> userOptions) { user = userOptions.Value; } [HttpGet] public string Get() { return $"姓名:{user.userName},年齡:{user.userAge} "; } }
輸出結(jié)果:姓名:趙一,年齡:18
嵌套讀取
我們對 appsettings.json 文件做一點小小的改動,增加一個子節(jié)點 child
:
{ "User": { "userName": "趙一", "userAge": 18, "child": { "userName": "趙一的崽", "userAge": 2 } } }
再對注冊的代碼做一點小小的修改:
services.Configure<UserOption>(Configuration.GetSection("User:child"));
輸出結(jié)果:姓名:趙一的崽,年齡:2
分實例讀取
這個時候需求又有變化了,需要同時讀取 User
與 child
節(jié)點的數(shù)據(jù),我們試試下面的方法看可行不可行:
// 注冊 services.Configure<UserOption>(Configuration.GetSection("User")); services.Configure<UserOption>(Configuration.GetSection("User:child")); // 控制器 public class HomeController : ControllerBase { private readonly UserOption user; private readonly UserOption child; public HomeController(IOptions<UserOption> userOptions, IOptions<UserOption> childOptions) { user = userOptions.Value; child = childOptions.Value; } [HttpGet] public string Get() { return $"姓名:{user.userName},年齡:{user.userAge} \r\n姓名:{child.userName},年齡:{child.userAge}"; } }
輸出結(jié)果很顯然滿足不了我們的需求:
姓名:趙一的崽,年齡:2 姓名:趙一的崽,年齡:2
有的小伙伴肯定會說,在實體模型內(nèi)在加一個子節(jié)點字段。這樣肯定是沒問題的,但是與常規(guī)讀取方式就沒什么兩樣了。
這里我要說的是分實例讀取,引入 Configure
的另一個重載方法,與之前不同的是多了一個參數(shù) name
:
public static IServiceCollection Configure<TOptions>(this IServiceCollection services, string name, IConfiguration config) where TOptions : class;
下面我們重新注冊:
services.Configure<UserOption>("father", Configuration.GetSection("User")); services.Configure<UserOption>("son", Configuration.GetSection("User:child"));
在控制器構(gòu)造函數(shù)中注入,也引入了一個新的接口對象:IOptionsMonitor
public class HomeController : ControllerBase { private readonly UserOption user; private readonly UserOption child; public HomeController(IOptionsMonitor<UserOption> userOptions, IOptionsMonitor<UserOption> childOptions) { user = userOptions.Get("father"); child = childOptions.Get("son"); } [HttpGet] public string Get() { return $"姓名:{user.userName},年齡:{user.userAge} \r\n姓名:{child.userName},年齡:{child.userAge}"; }
輸出結(jié)果:
姓名:趙一,年齡:18 姓名:趙一的崽,年齡:2
其實還有一個接口對象能實現(xiàn)這樣的效果:IOptionsSnapshot
,那 IOptionsMonitor
與 IOptionsSnapshot
有什么不同呢?請接著往下看。
IOptionsMonitor與IOptionsSnapshot的不同之處
我們先來看看微軟官方的注釋:
IOptionsMonitor
// // 摘要: // Used for notifications when TOptions instances change. // // 類型參數(shù): // TOptions: // The options type. public interface IOptionsMonitor<out TOptions> { // // 摘要: // Returns the current TOptions instance with the Microsoft.Extensions.Options.Options.DefaultName. TOptions CurrentValue { get; } // // 摘要: // Returns a configured TOptions instance with the given name. TOptions Get(string name); // // 摘要: // Registers a listener to be called whenever a named TOptions changes. // // 參數(shù): // listener: // The action to be invoked when TOptions has changed. // // 返回結(jié)果: // An System.IDisposable which should be disposed to stop listening for changes. IDisposable OnChange(Action<TOptions, string> listener); }
IOptionsSnapshot
// // 摘要: // Used to access the value of TOptions for the lifetime of a request. // // 類型參數(shù): // TOptions: // Options type. public interface IOptionsSnapshot<out TOptions> : IOptions<TOptions> where TOptions : class, new() { // // 摘要: // Returns a configured TOptions instance with the given name. TOptions Get(string name); }
從字面上理解,IOptionsMonitor
建議在配置信息更改后需要通知的場景下使用,所以多了個 OnChange
的方法;而 IOptionsSnapshot
翻譯過來的意思是:用于在請求的生命周期內(nèi)訪問配置,有點難以理解哈,我們接下來用代碼來驗證一下。
IOptionsMonitor 與 IOptionsSnapshot的生命周期
我們對實體模型再做一點小小的修改,增加一個 guid 字段,并給上默認(rèn)值:
public class UserOption { public string userName { get; set; } public int userAge { get; set; } public Guid guid { get; set; } = Guid.NewGuid(); }
我們再次運行程序:
father — 姓名:趙一,年齡:19,編號:e0d71f47-e8f1-4a6d-875e-2074c985f4a0 son — 姓名:趙一的崽,年齡:3,編號:d865151b-f9bf-4eff-bb4e-8ab6dc61160c
然后不停的刷新頁面會發(fā)現(xiàn),father
的編號沒有發(fā)生任何編號,而 son
的編號每次刷新都會改變。這是不是比較像我們注冊時所用到的三種模式:
services.AddScoped(); services.AddTransient(); services.AddSingleton()
其中 father
類似 AddSingleton
,son
則類似 AddScoped
與 AddTransient
。
大家可以在同一個方法里多次調(diào)用 childOptions.Get("son")
看看 son
到底時類似 AddScoped
還是 AddTransient
。
IOptionsMonitor的OnChange調(diào)用方式
userOptions.OnChange((user,name)=> { Console.WriteLine(user.userName +"-"+ name); });
無文件配置
無文件配置就是不需要以靜態(tài)文件的方式進行配置。相關(guān)信息在配置一次后就不用再做修改,我們可以采用無文件配置的方式,比如我們熟悉的 AddCors
跨域配置
services.AddCors(op => { op.AddPolicy(CorsName, set => { set.SetIsOriginAllowed(origin => true).AllowAnyHeader().AllowAnyMethod().AllowCredentials(); }); });
我們對之前的注冊方法進行一下改動:
services.Configure<UserOption>(c => { c.userName = "錢二"; c.userAge = 60; });
控制器注入采用常規(guī)的注入方式,最終輸出結(jié)果:姓名:錢二,年齡:60
分享一個源碼查看網(wǎng)站:https://source.dot.net/
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Linux?CentOS下docker部署Asp.Net?Core(.Net6)
這篇文章介紹了Linux?CentOS下docker部署Asp.Net?Core(.Net6)的方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12.Net行為型設(shè)計模式之命令模式(Command)
這篇文章介紹了.Net行為型設(shè)計模式之命令模式(Command),文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05創(chuàng)建ASP.NET?Core?Web應(yīng)用程序并介紹項目模板
這篇文章介紹了創(chuàng)建ASP.NET?Core?Web應(yīng)用程序的方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-02-02利用C#遠(yuǎn)程存取Access數(shù)據(jù)庫
目前,基于數(shù)據(jù)庫服務(wù)器的桌面管理程序和Web程序已經(jīng)有太多的應(yīng)用了,尤其是網(wǎng)絡(luò)的大量普及,孤立地數(shù)據(jù)庫管理系統(tǒng)無法勝任分布式管理應(yīng)用,但是面對基于Access數(shù)據(jù)庫的現(xiàn)有的桌面應(yīng)用我們也無法完全的摒棄。我們利用.Net 遠(yuǎn)程處理功能將連接和存取Access的行為封裝為一個遠(yuǎn)程對象,供網(wǎng)絡(luò)中其它客戶端通過調(diào)用該遠(yuǎn)程對象來存取實際的Access數(shù)據(jù)庫。我們以 C# 2005 為開發(fā)語言來實現(xiàn)上述功能。2008-04-04