.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" 公众号

相关推荐
向宇it6 小时前
【从零开始入门unity游戏开发之——C#篇25】C#面向对象动态多态——virtual、override 和 base 关键字、抽象类和抽象方法
java·开发语言·unity·c#·游戏引擎
向宇it8 小时前
【从零开始入门unity游戏开发之——C#篇24】C#面向对象继承——万物之父(object)、装箱和拆箱、sealed 密封类
java·开发语言·unity·c#·游戏引擎
坐井观老天12 小时前
在C#中使用资源保存图像和文本和其他数据并在运行时加载
开发语言·c#
贾光辉13 小时前
在.NET Core中使用异步多线程高效率的处理大量数据的最佳实践
.net core
pchmi15 小时前
C# OpenCV机器视觉:模板匹配
opencv·c#·机器视觉
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭16 小时前
C#都可以找哪些工作?
开发语言·c#
boligongzhu18 小时前
Dalsa线阵CCD相机使用开发手册
c#
向宇it1 天前
【从零开始入门unity游戏开发之——C#篇23】C#面向对象继承——`as`类型转化和`is`类型检查、向上转型和向下转型、里氏替换原则(LSP)
java·开发语言·unity·c#·游戏引擎·里氏替换原则
sukalot1 天前
windows C#-命名实参和可选实参(下)
windows·c#