如何在 ASP.Net Core 中使用 Configuration Provider
ASP.NET Core 是一個開源的,跨平臺的,精簡的模塊化框架,可用于構(gòu)建高性能,可擴展的web應(yīng)用程序, ASP.NET Core 中的數(shù)據(jù)配置常用 k-v 的形式存儲,值得注意的是,新的數(shù)據(jù)配置還支持 層級方式,在這篇文章中,我們將會討論如何在 ASP.NET Core 中去使用。
默認創(chuàng)建好的 ASP.Net Core 應(yīng)用程序中會有兩個json配置文件:appsettings.json 和 appsettings.Development.json, 如下圖所示:
使用 Json Provider
現(xiàn)在你可以使用 appsettings.json 來存放應(yīng)用程序的配置數(shù)據(jù)。比如:數(shù)據(jù)庫連接串,應(yīng)用程序特定配置,下面的代碼片段展示了如何使用 IConfigurationBuilder.AddJsonFile() 將 appsettings.json 添加到配置系統(tǒng)中。
public?static?IWebHostBuilder?CreateWebHostBuilder(string[]?args)?=>WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext,?config)?=>{var?env?=?hostingContext.HostingEnvironment;config.SetBasePath(env.ContentRootPath);config.AddJsonFile("appsettings.json",?optional:?false,?reloadOnChange:?true);}).UseStartup<Startup>();接下來看一下 appsettings.json 文件的具體內(nèi)容。
{"Logging":?{"LogLevel":?{"Default":?"Warning"}},"AllowedHosts":?"*","CustomKeys":?{"KeyA":?"ValueA","KeyB":?"ValueB"} }要想從 appsettings.json 中讀取到配置key,可以從 IConfiguration 實例中進行讀取,比如說:想要從 Controller 中讀取 Configuration,只需要通過依賴注入的方式將 Configuration 注入到 Controller 即可,如下代碼所示:
public?class?HomeController?:?Controller{private?readonly?ILogger<HomeController>?_logger;IConfiguration?_configuration;public?HomeController(ILogger<HomeController>?logger,?IConfiguration?configuration){_logger?=?logger;_configuration?=?configuration;}}下面的代碼片段展示了如何通過 IConfiguration 實例 從 appsettings.json 文件中讀取自定義的 CustomerKeys 節(jié)。
public?IActionResult?Index(){var?keyA?=?_configuration["CustomKeys:KeyA"];var?keyB?=?_configuration["CustomKeys:KeyB"];return?View();}下面是 HomeController 類的完整代碼。
public?class?HomeController?:?Controller{private?readonly?ILogger<HomeController>?_logger;IConfiguration?_configuration;public?HomeController(ILogger<HomeController>?logger,?IConfiguration?configuration){_logger?=?logger;_configuration?=?configuration;}public?IActionResult?Index(){var?keyA?=?_configuration["CustomKeys:KeyA"];var?keyB?=?_configuration["CustomKeys:KeyB"];return?View();}}除了默認生成的 appsettings.json,你還可以使用自定義的json文件給應(yīng)用程序提供特定的配置信息,換句話說,可以不用將所有的配置信息都放置在 appsettings.json 中,比如你可以創(chuàng)建一個自定義的 customsettings.json,然后在 CreateWebHostBuilder() 中將其灌入到配置系統(tǒng)中,如下代碼所示:
public?static?IWebHostBuilder?CreateWebHostBuilder(string[]?args)?=>WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext,?config)?=>{????????????????var?env?=?hostingContext.HostingEnvironment;string?pathOfCommonSettingsFile?=?env.ContentRootPath;config.SetBasePath(env.ContentRootPath);config.AddJsonFile("appsettings.json",?optional:?false,?reloadOnChange:?true);config.AddJsonFile($"appsettings.{env.EnvironmentName}.json",?optional:?true,?reloadOnChange:?true);config.AddJsonFile(Path.Combine(pathOfCommonSettingsFile,?"customsettings.json"),?optional:?true);}).UseStartup<Startup>();使用 Memory Provider
所謂的 Memory Provider 允許我們將應(yīng)用程序的一些配置直接配置到內(nèi)存,而不像傳統(tǒng)方式那樣一定要指定一個 物理文件, 下面的代碼展示了如何使用 Memory Provider 將 key-value 存放在內(nèi)存中。
var?builder?=?new?ConfigurationBuilder();var?profileCollection?=?new?Dictionary<string,?string>{{"AuthorProfile:FirstName",?"Joydip"},{"AuthorProfile:LastName",?"Kanjilal"},{"AuthorProfile:Address",?"Hyderabad,?India"}};builder.AddInMemoryCollection(profileCollection);Configuration?=?builder.Build();灌到內(nèi)存之后,接下來就可以通過 IConfiguration 實例獲取了,如下代碼所示:
var?firstName?=?_configuration["Profile:FirstName"];值得注意的是,和傳統(tǒng)的 ASP.NET 相比, ASP.NET Core 中的配置文件數(shù)據(jù)有變更時,默認情況下應(yīng)用程序是不會感知的,如果要做到感知的話,通常有兩種做法。
重啟應(yīng)用程序
調(diào)用 IConfigurationRoot.Reload()
對了,除了上文提到了json和memory,ASP.NET Core 還支持眾多的數(shù)據(jù)格式,如:JSON, XML,INI。
譯文鏈接:https://www.infoworld.com/article/3310608/how-to-use-configuration-providers-in-aspnet-core.html
總結(jié)
以上是生活随笔為你收集整理的如何在 ASP.Net Core 中使用 Configuration Provider的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET gRPC核心功能初体验
- 下一篇: Kubernetes中分布式存储Rook