前烟:
.NET Core 中取消了以往的 XML 节点配置文件,改用了 *.json 格式。
在 Startup.cs 文件中,构造方法 build appsetting.json 文件,
本文主要对解析配置文件的官方工具类做总结;
一、appsettings.json 文件
在新建的 Core Web 项目中,默认会有一个全局的配置变量:IConfigurationRoot
提供了索引器、GetSection 方法;
{ "Host": "http://localhost:5966/", "Title": "Hello World", "SiteKeywords": "asp.net, c#, asp.net core, asp.net entityframework core", "Description": "DotNetClub: asp.net core", "ConnectionString": "Data Source=localhost;Initial Catalog=dbName;User Id=userName;Password=pwd;", "Redis": { "EndPoints": [ "localhost", "6379" ], "Password": "", "Db": "" }, "Site": { "Host": "http://localhost:5966", "Title": "Hello World", "Description": "DotNetClub: asp.net core", "AllowRegister": true, "VerifyRegisterUser": false, "AdminUserList": [] }, "CookieName": "DotNetClub.User", "Categories": [ { "Key": "share", "Name": "分享" }, { "Key": "ask", "Name": "问答" }, { "Key": "job", "Name": "招聘" } ] }
获取根节点数据:
Configuration["ConnectionString"]
Configuration["Title"]
获取节点数据:
services.Configure<RedisOptions>(Configuration.GetSection("Redis").Bind)
重点记录的是这个 Microsoft.Extensions.Options.ConfigurationExtensions 提供的 IOptions
Configure 方法可以将 appsettings.json 中的配置绑定某一个实体对象上。如:
public class RedisOptions { /// <summary> /// Redis end points, such as "{host or ip}:{port}" /// </summary> public string[] EndPoints { get; set; } /// <summary> /// Redis password /// </summary> public string Password { get; set; } /// <summary> /// Default redis database /// </summary> public int Db { get; set; } }
完成这样的一个过程就是 Configure 类实现了一个依赖注入;
时间: 2024-10-21 01:14:08