.net core 读取配置文件
1 使用文件配置提供程序,配置来源可以是json文件、ini文件和xml文件
以json文件作为配置来源读取数据库连接配置实例程序步骤如下:
1)创建一个asp.net coe web api 应用程序 (.net 5 框架)
把配置文件属性 ”复制到输出目录“设置为”如果较新则复制“
2)在项目的 Startup.cs 设置如下代码
public Startup(IWebHostEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); }
3) 读取配置工具类 ConfigurationHelper 如下
/// <summary> /// 读取配置文件工具类 /// </summary> public class ConfigurationHelper { private static IConfiguration _config; public static void Configure(IConfiguration configuration) { _config = configuration; } /// <summary> /// 获取配置文件中指定键的配置值 /// </summary> /// <param name="key">配置键名</param> /// <returns></returns> public static string GetKey(string key) { return _config[key]; } /// <summary> /// 获取配置文件中指定键的配置值 /// </summary> /// <param name="key">配置键名</param> /// <returns></returns> public static string GetSection(string key) { return _config[key]; } /// <summary> /// 使用选项模式对配置进行强类型访问 /// </summary> /// <param name="key">指定配置节</param> /// <param name="instance">强类型实例</param> public static void BindConfiguration(string key,object instance) { _config.GetSection(key).Bind(instance); } }
4) 在 Startup.cs 中的 Configure 添加如下代码初始化配置
// 配置 ConfigurationHelper ConfigurationHelper.Configure(Configuration);
5)配置文件 appsettings.json 如下
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", // 单键值对 "stringKey": "stringKeyValue", // 配置组 "groupKey": { "Default": "Server=localhost,1433; Database=MsDemo_Identity; User=sa; Password=yourStrong(!)Password", "Conn1": "Server=localhost,1500; Database=MsDemo_Identity; User=sa; Password=yourStrong(!)Password", "numberKey": 1, "boolKey": true }, // 使用选项模式提供对配置的强类型访问 "IdentityServerData": { "IdentityResources": [ { "Name": "openid", "Enabled": true, "Required": true, "DisplayName": "Your user identifier", "UserClaims": [ "sub" ] }, { "Name": "profile", "Enabled": true, "DisplayName": "User profile", "Description": "Your user profile information (first name, last name, etc.)", "Emphasize": true, "UserClaims": [ "name", "family_name", "given_name", "middle_name", "nickname", "preferred_username", "profile", "picture", "website", "gender", "birthdate", "zoneinfo", "locale", "updated_at" ] } ], "ApiScopes": [ { "Name": "skoruba_identity_admin_api", "DisplayName": "skoruba_identity_admin_api", "Required": true, "UserClaims": [ "role", "name" ] } ] } }
6)读取配置代码如下
[ApiController] [Route("api/[controller]/[action]")] public class ConfigController : ControllerBase { [HttpGet] public IActionResult GetConfig() { // 读取 单键值对 string key1Val = ConfigurationHelper.GetKey("stringKey").ToString(); // 读取 配置组 string groupKey_default = ConfigurationHelper.GetSection("groupKey:Default"); string groupKey_Conn1 = ConfigurationHelper.GetSection("groupKey:Conn1"); long groupKey_numberKey = Convert.ToInt64(ConfigurationHelper.GetSection("groupKey:numberKey")); bool groupKey_boolKey = Convert.ToBoolean(ConfigurationHelper.GetSection("groupKey:boolKey")); // 使用选项模式对配置进行强类型访问 IdentityServerData identityServerData = new IdentityServerData(); ConfigurationHelper.BindConfiguration(nameof(IdentityServerData), identityServerData); return new JsonResult("ok"); } }
7)与.net framework读取配置对比
以前.net framework读取配置文件(一般为Web.config/app.config)一般是先添加System.Configuration.dll引用,然后使用ConfigurationManager读取配置,如下:
System.Configuration.ConfigurationManager.ConnectionStrings["DBConnect"].ToString().Trim()
代码 git 地址:
https://gitee.com/codechen01/Demo.git
注意:
1 .net 5 可以不添加以下依赖包:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Abstractions
Microsoft.Extensions.Configuration.Json
2 如果 appsettings.json 和 appsettings.Development.json 都配置了同一个键,则取最后添加的配置文件的值为准。