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

控制台项目中,演示示例

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

参考项目地址

END 欢迎关注 "ShareFlow" 公众号

相关推荐
IT技术分享社区3 小时前
C#实战:使用腾讯云识别服务轻松提取火车票信息
开发语言·c#·云计算·腾讯云·共识算法
△曉風殘月〆10 小时前
WPF MVVM入门系列教程(二、依赖属性)
c#·wpf·mvvm
逐·風12 小时前
unity关于自定义渲染、内存管理、性能调优、复杂物理模拟、并行计算以及插件开发
前端·unity·c#
m0_6569747415 小时前
C#中的集合类及其使用
开发语言·c#
九鼎科技-Leo15 小时前
了解 .NET 运行时与 .NET 框架:基础概念与相互关系
windows·c#·.net
九鼎科技-Leo17 小时前
什么是 ASP.NET Core?与 ASP.NET MVC 有什么区别?
windows·后端·c#·asp.net·mvc·.net
.net开发17 小时前
WPF怎么通过RestSharp向后端发请求
前端·c#·.net·wpf
小乖兽技术18 小时前
C#与C++交互开发系列(二十):跨进程通信之共享内存(Shared Memory)
c++·c#·交互·ipc
幼儿园园霸柒柒18 小时前
第七章: 7.3求一个3*3的整型矩阵对角线元素之和
c语言·c++·算法·矩阵·c#·1024程序员节
平凡シンプル20 小时前
C# EF 使用
c#