日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

.NET 云原生架构师训练营(模块二 基础巩固 配置)--学习笔记

發布時間:2023/12/4 asp.net 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 .NET 云原生架构师训练营(模块二 基础巩固 配置)--学习笔记 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2.2.3 核心模塊--配置

  • IConfiguration

  • Options

ASP.NET Core 中的配置:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-5.0

IConfiguration

  • IConfiguration 的使用

  • 層級對象配置到 key-value 鍵值對轉換

  • 通過環境變量修改日志級別

  • 通過命令行修改日志級別

IConfiguration 的使用

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

這樣可以得到自己添加的配置

層級對象配置到 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

通過環境變量修改日志級別

在 launcSettings.json 中添加 Trace 日志級別

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

在 CreateHostBuilder 的時候添加環境變量配置

config.AddEnvironmentVariables();

啟動程序,輸出如下:

Default Log Level: Trace

通過命令行修改日志級別

CreateHostBuilder

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

在命令行中設置

set Logging__LogLevel__Default=Warning

Options

  • 通過 ConfigurationBinder 操作 Options

  • 通過 Configure 綁定 Option

通過 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); }

啟動程序,訪問:https://localhost:5001/config/option

輸出如下:

{"name":"Mingson","age":25}

通過 Get 的方式

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

通過 Configure 綁定 Option

IOptions

  • 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; }

啟動程序,修改配置,刷新瀏覽器,可以獲取到修改后的配置

可命名的配置

appsettings.json

"Jack": {"Name": "Jack","Age": 16},"Peter": {"Name": "Peter","Age": 18}

MyOption.cs

public const string PETER = "Peter";public const string JACK = "Jack";

ConfigureServices

services.Configure<MyOption>("Peter", Configuration.GetSection("Peter")); services.Configure<MyOption>("Jack", Configuration.GetSection("Jack"));

ConfigController

_myOption = myOption.Get(MyOption.PETER); _myOption = myOption.Get(MyOption.JACK);

啟動程序即可讀取不同命名的配置

IOptionsMonitor

public ConfigController(IConfiguration configuration, IOptionsMonitor<MyOption> myOption) {_configuration = configuration;_myOption = myOption.CurrentValue;// 配置變化處理myOption.OnChange(option =>{}); }

option 驗證

屬性驗證標簽

namespace HelloApi {public class MyConfigOptions{public const string MyConfig = "MyConfig";[RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$")]public string Key1 { get; set; }[Range(0, 1000, ErrorMessage = "Value for {0} must be between {1} and {2}.")]public int Key2 { get; set; }public int Key3 { get; set; }} }

綁定后校驗

ConfigureServices

services.AddOptions<MyOption>().Bind(Configuration.GetSection("MyOption")).ValidateDataAnnotations();

MyOption

[Range(1, 20)] public int Age { get; set; }

啟動程序,輸出如下:

OptionsValidationException: DataAnnotation validation failed for members: 'Age' with the error: 'The field Age must be between 1 and 20.'.

PostConfigure

當配置被讀取出來的時候會被執行

services.PostConfigure<MyOption>(option => {if (option.Age == 20){option.Age = 19;} });

GitHub源碼鏈接:

https://github.com/MINGSON666/Personal-Learning-Library/tree/main/ArchitectTrainingCamp/HelloApi

課程鏈接

.NET云原生架構師訓練營講什么,怎么講,講多久

歡迎各位讀者加入微信群一起學習交流,

在公眾號后臺回復“加群”即可~~

總結

以上是生活随笔為你收集整理的.NET 云原生架构师训练营(模块二 基础巩固 配置)--学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。