第四十三节:再探配置系统(多个appsettings.json/环境/各种读取方式)、机密文件、选项模式

一. 复习

1. appsettings.json 和 appsettings.{Environment}.json

  在开发环境中,appsettings.Development.json 配置会覆盖在 appsettings.json 中找到的值,如果读取的key在Development文件中没有,则去appsettings.json中读取

  在生产环境中,appsettings.Production.json 配置会覆盖在 appsettings.json 中找到的值,如果读取的key在Production文件中没有,则去appsettings.json中读取

测试:

  A. 开发环境中的结果: userPwd: ypf001_Development,userGender: man

  B. 生产环境中的结果:   userPwd: ypf001_Production,userGender: man

代码分享:

        /// <summary>
        /// 测试appsettings各种变种
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string TestAppsettings()
        {
            string userPwd = Configuration["userPwd"];
            string userGender= Configuration["userGender"];
            return $"userPwd:{userPwd},userGender:{userGender}";
        }

 

2. 判断生产、开发、测试、自定义环境

  ASP.NET Core 在应用启动时读取环境变量 ASPNETCORE_ENVIRONMENT, ASPNETCORE_ENVIRONMENT 可设置为任意值,但框架仅支持三个值:Development(开发)、Staging(测试)和 Production(生产)。 如果未设置 ASPNETCORE_ENVIRONMENT,则默认为 Production(即生产环境)。

 (1). 在program文件中

   app.Environment.IsDevelopment()

 (2). 在action中

   注入:[FromServices] IHostEnvironment evn,然后 evn.IsDevelopment()

还有其它方法:

                开发环境:evn.IsDevelopment()

                测试环境:evn.IsStaging()

                生产环境:evn.IsProduction()

                自定义环境:evn.IsEnvironment("ypf")

PS:如何手动修改环境变量 ASPNETCORE_ENVIRONMENT ,详见 https://www.cnblogs.com/yaopengfei/p/10904178.html

代码分享:

        /// <summary>
        /// 测试环境的读取
        /// </summary>
        /// <param name="evn"></param>
        /// <returns></returns>
        [HttpPost]
        public string TestEnvironment([FromServices] IHostEnvironment evn)
        {
            string msg = $"是开发环境:{evn.IsDevelopment()}," +
                $"是测试环境:{evn.IsStaging()}," +
                $"是生产环境:{evn.IsProduction()}," +
                $"是自定义环境:{evn.IsEnvironment("ypf")}";
            return msg;
        }

 

二. 配置系统

1. 如何使用

  (默认已经加载了appsettings.json、appsettings.Development.json、appsettings.Production.json文件)

 (1). 控制器中

     注入 IConfiguration configuration,使用即可

 (2). Program.cs文件中

  var builder = WebApplication.CreateBuilder(args);  然后使用builder.Configuration["userPwd"] 即可

关于多层的读取规则参考之前文章:https://www.cnblogs.com/yaopengfei/p/10975759.html

program中代码分享:

//读取配置文件
Console.WriteLine("测试读取配置文件:" + builder.Configuration["userPwd"]);
Console.WriteLine("测试用法方法配置文件:" + builder.Configuration.GetValue<string>("userPwd"));
Console.WriteLine("读取用户机密文件:" + builder.Configuration["testUserSecret"]);

 

2. 方法和绑定

(1). 常用方法: GetValue<T>、GetSection、GetChildren、Exits

(2). 绑定:读取配置文件的内容绑定到一个类上,通过GetSection+Bind实现 (详见下面选项模式的代码实操)

详细用法参考之前的文章:https://www.cnblogs.com/yaopengfei/p/10975759.html

3. 其它文件

  (比如其它json文件、xml文件、ini文件等)

 需要在Program中进行注册一下,先设置当前目录,然后通过AddJsonFile、AddXmlFile加载进来即可

 注意:这些配置文件的属性都要改为始终复制

注册代码分享

//注册其它配置文件
//1. 设置当前目录为基础目录(后面则可以用相对路径)
builder.Configuration.SetBasePath(Directory.GetCurrentDirectory());
//2.加载json文件 (配置后面两个参数为true,当配置文件发生变化的时候,会自动更新加载,而不必重启整个项目)
builder.Configuration.AddJsonFile("MyConfig/ypf1.json", optional: true, reloadOnChange: true);
//3.加载xml文件
builder.Configuration.AddXmlFile("MyConfig/ypf2.xml");

读取代码

        /// <summary>
        /// 测试读取其它配置文件
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string TestOtherConfig()
        {
            string schoolName = Configuration["schoolName"];
            string k0content = Configuration["section0:key0"];
            return $"ypf1.json中读取的内容为:{schoolName},ypf2.xml中读取的内容为:{k0content}";
        } 

 

三. 机密文件

详细用法见之前文章:https://www.cnblogs.com/yaopengfei/p/12129746.html

EFCore链接字符串写入机密程序中:https://www.cnblogs.com/yaopengfei/p/11633385.html    

用法:

   (1). 选中项目右键→管理用户机密,则 生成 或 打开机密文件

   (2). xxx.csporj中的 <UserSecretsId>4a888c0c-6db9-4db6-b971-882f7609c643</UserSecretsId>,表示机密文件对应磁盘文件夹名称

   (3). 磁盘文件夹路径  %APPDATA%\microsoft\UserSecrets\

结论:当appsetting.json 和 机密文件中都有这个字符串,优先读取的是机密文件

 

四. 选项模式

1. 含义

  选项模式使用类来提供对相关设置组的强类型访问

2. 选项类

 A.必须是包含公共无参数构造函数的非抽象类。

 B.类型的所有公共读写属性都已绑定。

 C.字段不是绑定的

3. 实操

 写法1:GetSection+Bind方法

   项目启动后,json文件修改,那么读取的是修改后的文件

 写法2:GetSection+Get方法 【更加简介】

   项目启动后,json文件修改,那么读取的是修改后的文件

 写法3:

  A. 现在Program文件中注册

  B. 在控制器中通过IOptions<UserInfo> userInfo  或IOptionsSnapshot<UserInfo> userInfo 进行注入

注:这种写法项目启动后,无法读取修改后的json文件,如果想读取修改后的,需要使用IOptionsSnapshot

(详见官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/options?view=aspnetcore-6.0)

类代码

  public class UserInfo
    {
        public string id { get; set; }
        public string name { get; set; }
    }

配置文件代码

{
    //测试选项模式
    "UserInfo": {
        "id": "001",
        "name": "ypf"
    }
}

选项模式注册代码(program.cs)

var builder = WebApplication.CreateBuilder(args);
//注册选项模式类
builder.Services.Configure<UserInfo>(builder.Configuration.GetSection("UserInfo"));

最终读取代码

        private readonly IConfiguration Configuration;
        private readonly UserInfo _user;
        public Test1Controller(IConfiguration configuration,IOptions<UserInfo> userInfo)
        {
            Configuration = configuration;
            _user = userInfo.Value;
        }
 
       /// <summary>
        /// 测试选项模式
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string TestChooseMode()
        {
            string msg = "";
            //写法1
            {
                UserInfo userInfo = new UserInfo();
                Configuration.GetSection("UserInfo").Bind(userInfo);
                msg = $"id为:{userInfo.id},name为:{userInfo.name}";
            }
            //写法2
            {
                UserInfo userInfo = Configuration.GetSection("UserInfo").Get<UserInfo>();
                msg = $"id为:{userInfo.id},name为:{userInfo.name}";
            }
            //写法3
            {
                msg = $"id为:{_user.id},name为:{_user.name}";
            }
            return msg;
        }

 

 

 

 

 

 

 

!

  • 作       者 : Yaopengfei(姚鹏飞)
  • 博客地址 : http://www.cnblogs.com/yaopengfei/
  • 声     明1 : 如有错误,欢迎讨论,请勿谩骂^_^。
  • 声     明2 : 原创博客请在转载时保留原文链接或在文章开头加上本人博客地址,否则保留追究法律责任的权利。
 
posted @ 2022-05-24 09:11  Yaopengfei  阅读(595)  评论(2编辑  收藏  举报