zoukankan      html  css  js  c++  java
  • 2.2.3 核心模块--理解.NetCore Configuration 配置管理

    官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-5.0

    一、IConfiguration 的使用

    1.1基本使用

    appsettings.json

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*"
    }
    

    新增 ConfigController.cs

    namespace HelloApi.Controllers
    {
        [ApiController]
        [Route("[controller]")]
        public class ConfigController : Controller
        {
            private readonly IConfiguration _configuration;
    
            public ConfigController(IConfiguration configuration)
            {
                _configuration = configuration;
            }
    
            [HttpGet]
            public IActionResult GetConfigurations()
            {
                var result = new List<string>();
    
                foreach (var key in _configuration.AsEnumerable())
                {
                    result.Add($"Key: {key.Key}, value: {key.Value}");
                }
    
                return Ok(result);
            }
        }
    }

    启动程序,访问:https://localhost:5001/config

    不仅得到 appsettings.json 的配置, 还可以得到环境变量配置

    可以在 ConfigureAppConfiguration 中清除所有配置,再添加自己需要的配置,后面添加的配置会覆盖前面的配置

    .ConfigureAppConfiguration((hostingContext, config) =>
    {
        config.Sources.Clear();
    
        var env = hostingContext.HostingEnvironment;
    
        config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
    })

    启动程序,访问:https://localhost:5001/config

    这样可以得到自己添加的配置

    1.2层级对象配置到 key-value 键值对转换

    appsettings.json文件

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*"
    }

    通过冒号读取下一级配置(Windows),Linux 上通过下划线。

    [HttpGet]
    public IActionResult GetConfigurations()
    {
        var result = new List<string>();
    
        //foreach (var key in _configuration.AsEnumerable())
        //{
        //    result.Add($"Key: {key.Key}, value: {key.Value}");
        //}
    
        return Content(string.Format("Default Log Level: {0}", _configuration["Logging:LogLevel:Default"]));
    }

    启动程序,输出如下:

    Default Log Level: Debug

    1.3通过环境变量修改日志级别

    在 launcSettings.json 中添加 Trace 日志级别

    "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development",
            "Logging__LogLevel__Default": "Trace"
          }

    在 CreateHostBuilder 的时候添加环境变量配置

    config.AddEnvironmentVariables();

    启动程序,输出如下:

    Default Log Level: Trace

    1.4通过命令行修改日志级别

    CreateHostBuilder

    config.AddCommandLine(source =>
    {
        source.Args = args;
    });

    在命令行中设置

    set Logging__LogLevel__Default=Warning

    二、Options

    2.1通过 ConfigurationBinder 操作 Options

     新建 MyOption.cs

    namespace HelloApi
    {
        public class MyOption
        {
            public string Name { get; set; }
    
            public int Age { get; set; }
        }
    }

    在 appsettings.json 中新增一个节点

    "MyOption": {
        "Name": "Mingson",
        "Age": 25 
      },

    在 ConfigureServices 中绑定

    var myOption = new MyOption();
    Configuration.GetSection("MyOption").Bind(myOption);
    // 单例注入到全局中
    services.AddSingleton(myOption);

    在 ConfigController 中注入,与获取

    private readonly MyOption _myOption;
    
    public ConfigController(IConfiguration configuration, MyOption myOption)
    {
        _configuration = configuration;
        _myOption = myOption;
    }
    
    [HttpGet("option")]
    public IActionResult GetOption()
    {
        return Ok(_myOption);
    }

    通过 Get 的方式

    myOption = Configuration.GetSection("MyOption").Get<MyOption>();

    2.2通过 Configure 绑定 Option

    • IOptions 被注册为 singletone,不支持为可命名的配置
    • IOptionsSnapshot 被注册为 scoped,支持为可命名的配置
    • IOptionsMonitor 被注册为 singletone,会被通知,支持重载配置,支持为可命名的配置

    IOptions

    // 直接注入到容器中
    services.Configure<MyOption>(Configuration.GetSection("MyOption"));

    通过 IOptions 注入

    public ConfigController(IConfiguration configuration, IOptions<MyOption> myOption)
    {
        _configuration = configuration;
        _myOption = myOption.Value;
    }

    IOptionsSnapshot

    public ConfigController(IConfiguration configuration, IOptionsSnapshot<MyOption> myOption)
    {
        _configuration = configuration;
        _myOption = myOption.Value;
    }

    启动程序,修改配置,刷新浏览器,可以获取到修改后的配置

    IOptionsMonitor

    public ConfigController(IConfiguration configuration, IOptionsMonitor<MyOption> myOption)
    {
        _configuration = configuration;
        _myOption = myOption.CurrentValue;
    
        // 配置变化处理
        myOption.OnChange(option =>
        {
    
        });
    }
    
    
  • 相关阅读:
    统计nginx进程占用的物理内存
    使用网络用户命令行工具的/passwordreq:yes
    MSSQL 日期查询 包含NULL值
    错误信息:"OraOLEDB.Oracle" 返回了消息 "ORA-12154: TNS: 无法解析指定的连接标识符
    SQL Server连接Oracle FAIL
    为SSRS配置SMTP服务器身份验证
    约束
    VS2012
    Reporting services
    MSSQL grant权限
  • 原文地址:https://www.cnblogs.com/duyao/p/15391924.html
Copyright © 2011-2022 走看看