ASP.NET Core 是一個開源的,跨平臺的,精簡的模塊化框架,可用於構建高性能,可擴展的web應用程序, ASP.NET Core 中的數據配置常用 k-v
的形式存儲,值得注意的是,新的數據配置還支持 層級方式
,在這篇文章中,我們將會討論如何在 ASP.NET Core 中去使用。
默認創建好的 ASP.Net Core 應用程序中會有兩個json配置文件:appsettings.json
和 appsettings.Development.json
, 如下圖所示:
使用 Json Provider
現在你可以使用 appsettings.json
來存放應用程序的配置數據。比如:數據庫連接串,應用程序特定配置,下面的代碼片段展示瞭如何使用 IConfigurationBuilder.AddJsonFile()
將 appsettings.json 添加到配置系統中。
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
文件的具體內容。
{
"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 節。
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文件給應用程序提供特定的配置信息,換句話說,可以不用將所有的配置信息都放置在 appsettings.json
中,比如你可以創建一個自定義的 customsettings.json
,然後在 CreateWebHostBuilder() 中將其灌入到配置系統中,如下代碼所示:
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 允許我們將應用程序的一些配置直接配置到內存,而不像傳統方式那樣一定要指定一個 物理文件
, 下面的代碼展示瞭如何使用 Memory Provider 將 key-value
存放在內存中。
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();
灌到內存之後,接下來就可以通過 IConfiguration 實例獲取了,如下代碼所示:
var firstName = _configuration["Profile:FirstName"];
值得注意的是,和傳統的 ASP.NET 相比, ASP.NET Core 中的配置文件數據有變更時,默認情況下應用程序是不會感知的,如果要做到感知的話,通常有兩種做法。
-
重啓應用程序 -
調用 IConfigurationRoot.Reload()
對了,除了上文提到了json和memory,ASP.NET Core 還支持衆多的數據格式,如:JSON, XML,INI。
譯文鏈接:https://www.infoworld.com/article/3310608/how-to-use-configuration-providers-in-aspnet-core.html
本文分享自微信公衆號 - 一線碼農聊技術(dotnetfly)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。