Loading... # 选项读取默认值 > 环境:.NET 7.0 项目:WebApi ## 创建静态服务提供器 ### 创建静态类 ```c# public static class Util { /// <summary> /// 服务提供器 /// </summary> public static IServiceProvider? ServiceProvider { get; set; } /// <summary> /// 获取服务 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T? GetService<T>() { return ServiceProvider.GetService<T>(); } } ``` ### 给服务提供器赋值(所有服务注册完后在其最后赋值) ```c# var builder = WebApplication.CreateBuilder(args); builder.Services.AddMvc(); // 示例非必要 .... .... .... // 服务提供器 Util.ServiceProvider = builder.Services.BuildServiceProvider(); ``` ## 读取默认配置文件 > appsetting.json ### json文件内容 ```json "JwtConst": { "SecurityKey": "TG&SnapEbCp4Gj9dNehz3B3NJgzwb@zIdDl4Lr52xqm6Ra6Xh^ONdK4dr9EzmKraYS*sUCBkRhB1&bwHvuB^vcdFsGfFKMwOt9H", "Domain": "https://*7210" } ``` ### 创建与json内容类型一致的类(命名后缀加Options) ```c# public class JwtConstOptions { public const string JwtConst = "JwtConst"; public string SecurityKey { get; set; } public string Domain { get; set; } } ``` ### 使用 ```c# public void GetJwtStr() { var jwtConfig = Util.GetService<IConfiguration>() ?.GetSection(JwtConstOptions.JwtConst).Get<JwtConstOptions>(); var key = jwtConfig.SecurityKey; var domain = jwtConfig.Domain; } ``` ## 读取自定义配置 > dbsettings.json ### json文件内容 ```json { "DbConnConfig": { "ConnStr": "Database=***;Data Source=***;Port=3306;User Id=***;Password=***;Charset=utf8mb4;", "DbType": 0 } } ``` ### 添加配置读取路径 ```c# builder.Configuration.AddJsonFile("dbsettings.json"); ``` ### 使用 与读取默认文件步骤一致 最后修改:2023 年 02 月 23 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 1 如果觉得我的文章对你有用,请随意赞赏