您当前的位置:首页 > 文章 > .NET Core Configuration 配置项知识点一网打尽!

.NET Core Configuration 配置项知识点一网打尽!

作者:雨太阳 时间:2024-06-04 阅读数:239 人阅读

控制台项目中,演示示例

1.自定义 Dictionary Config 内存字典模式

dotnet add package Microsoft.Extensions.Configuration

IConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddInMemoryCollection(new Dictionary<string, string>()
{
    {"key1","v1"},
    {"key2","v2"},
    {"key3","v3"},
    {"key4:key5","v4-v5"},
}!);
IConfigurationRoot configurationRoot = builder.Build();
IConfiguration config = configurationRoot;

Console.WriteLine(configurationRoot["key1"]);
Console.WriteLine(configurationRoot["key2"]);

IConfigurationSection section = config.GetSection("key4");

Console.WriteLine(section["key5"]);
Console.WriteLine(config["key4:key5"]);
Console.WriteLine(configurationRoot["key4:key5"]);

2. 命令替换模式/提供程序

//dotnet add package Microsoft.Extensions.Configuration.CommandLine var bulider = new ConfigurationBuilder(); //bulider.AddCommandLine(ages); #region 命令替换模式/提供程序 var mapper = new Dictionary<string, string>() {     {"-k1","CommandLineKey1" } }; bulider.AddCommandLine(ages, mapper); //结果就会变为 LineKey:k3 //通常用于 短命名,快捷命名 #endregion var configurationRoot = bulider.Build(); //属性--> 调试里面设置的启动参数 Console.WriteLine($"LineKey:{configurationRoot["CommandLineKey1"]}"); Console.WriteLine($"LineKey:{configurationRoot["CommandLineKey2"]}"); Console.ReadKey();

3.环境变量提供应用程序

//dotnet add package Microsoft.Extensions.Configuration.EnvironmentVariables
var builder = new ConfigurationBuilder();
builder.AddEnvironmentVariables();
var configurationRoot = builder.Build();
//属性--> 调试里面 设置的环境变量的 参数
Console.WriteLine($"key1:{configurationRoot["key1"]}");
#region 分层键
Console.WriteLine($"key3:{configurationRoot.GetSection("select")["key3"]}");
Console.WriteLine($"key4:{configurationRoot.GetSection("select:key3")["key4"]}");
#endregion
#region 前缀过滤
builder.AddEnvironmentVariables("cy_");
configurationRoot = builder.Build();
Console.WriteLine($"cy key1:{configurationRoot["key1"]}");
#endregion

4.文件配置提供程序

//dotnet add package Microsoft.Extensions.Configuration.Ini
//dotnet add package Microsoft.Extensions.Configuration.Json
//dotnet add package Microsoft.Extensions.Configuration.NewtonsoftJosn
//dotnet add package Microsoft.Extensions.Configuration.Xml
//dotnet add package Microsoft.Extensions.Configuration.UserSecrets
var builder = new ConfigurationBuilder();
//optional:false 检测文件存不存在 默认false,当是true的时候,如果文件不存在则会报错~
//reloadOnChange 是否读取文件变更
builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
builder.AddIniFile("appsettings.ini", optional: false, reloadOnChange: true);
var configurationRoot = builder.Build();
Console.WriteLine($"key1:{configurationRoot["key1"]}");
Console.WriteLine($"key2:{configurationRoot["key2"]}");
Console.WriteLine($"key3:{configurationRoot["key3"]}");
Console.ReadKey();
Console.WriteLine($"key1:{configurationRoot["key1"]}");
Console.WriteLine($"key2:{configurationRoot["key2"]}");
Console.WriteLine($"key3:{configurationRoot["key3"]}");
var connectionString = configurationRoot["DatabaseSettings:ConnectionString"];
var logLevel = configurationRoot["Logging:LogLevel"];
var apiKey = configurationRoot["ApiSettings:ApiKey"];

Console.WriteLine($"Connection String: {connectionString}");
Console.WriteLine($"Log Level: {logLevel}");
Console.WriteLine($"API Key: {apiKey}");
Console.ReadKey();


5.配置变更监听

var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var configurationRoot = builder.Build();
IChangeToken changeToken = configurationRoot.GetReloadToken();
//注意:Debug 模式下在 \bin\Debug\net8.0\的生成文件下去修改文件内容 才生效!!!
////只能获取一次变更!
//changeToken.RegisterChangeCallback(state =>
//{
//    Console.WriteLine($"key1---->:{configurationRoot["key1"]}");
//    Console.WriteLine($"key2---->:{configurationRoot["key2"]}");
//    Console.WriteLine($"key3---->:{configurationRoot["key3"]}");
//}, configurationRoot);

//多次变更都能捕获到!
ChangeToken.OnChange(() => configurationRoot.GetReloadToken(), () =>
{
    Console.WriteLine($"key1---->:{configurationRoot["key1"]}");
    Console.WriteLine($"key2---->:{configurationRoot["key2"]}");
    Console.WriteLine($"key3---->:{configurationRoot["key3"]}");
});

Console.ReadKey();

6.配置绑定

//dotnet add package Microsoft.Extensions.Configuration.Binder
//1.绑定已有对象
//2.绑定私有属性
var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var config = new AppSettingConfigModel()
{
    Key1 = "Key1",
    Key2 = "Key2",
    //Key4 = 4
};
var configurationRoot = builder.Build();
configurationRoot.Bind(config); //以appsettings.json 的为准

//多级设置
configurationRoot.GetSection("OrderService").Bind(config, options =>
{
    //private 的私有属性,也可以赋值进去
    options.BindNonPublicProperties = true;
});

Console.WriteLine($"Key2---->:{config.Key1}");
Console.WriteLine($"Key2---->:{config.Key2}");
Console.WriteLine($"Key4---->:{config.Key4}");

WebApi项目中,演示示例


WebApplicationConfig项目
  • ? Startup.cs 基础项

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

7.结合IOption<> 使用 选项框架

//绑定整个 appsettings.json 到 AppSettings 类
services.Configure<ConfigOptionsModel>(Configuration);

private readonly IOptionsMonitor<ConfigOptionsModel> _options;

//IOptionsSnapshot
//IOptionsMonitor (单例的时候拿到变更项)
public WeatherForecastController(IOptionsMonitor<ConfigOptionsModel> options)
{
    _options = options;
    _options.OnChange(option =>
    {
        Console.WriteLine($"change-->{option.key1}");
    });
}
[HttpGet]
public string Get()
{
    Console.WriteLine(_options.CurrentValue.key1);
    Console.WriteLine(_options.CurrentValue.key2);
    Console.WriteLine(_options.CurrentValue.key3);
    Console.WriteLine(_options.CurrentValue.key4);
    return "1";}

8.为选项框架添加验证逻辑

//为选项框架添加验证逻辑
services.AddOptions<ConfigOptionsModel>().Configure(op =>
{
    Configuration.Bind(op);
})
////属性设置验证 [Range(1,200)]
//.ValidateDataAnnotations();

//自定义属性验证 ConfigOptionsVaildateOptions
.Services.AddSingleton<IValidateOptions<ConfigOptionsModel>, ConfigOptionsVaildateOptions>();

////自定义设置
//.Validate(x =>
//{
//    return x.key4 <= 200;
//}, "key4 不能大于200");

//动态设置参数
services.PostConfigure<ConfigOptionsModel>(option =>
{
    option.key1 += "===>PostConfigure";
});
namespace WebApplicationConfig 文件
public class ConfigOptionsModel
{
    public string key1 { get; set; }
    public string key2 { get; set; }
    public string key3 { get; set; }
    [Range(1,500)]
    public int key4 { get; set; }
}
public class ConfigOptionsVaildateOptions : IValidateOptions<ConfigOptionsModel>
{
    public ValidateOptionsResult Validate(string name, ConfigOptionsModel options)
    {
        if (options.key4 > 300) 
        {
            throw new ValidationException("key4 不能大于300");
        }
        return ValidateOptionsResult.Success;
    }
}

参考项目地址

  • ? https://github.com/goodluckily/ConsoleAppConfig

  • ? https://github.com/goodluckily/WebApplicationConfig

本站大部分文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了您的权益请来信告知我们删除。邮箱:1451803763@qq.com