RuoVea.ExConfig 2.0.0.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package RuoVea.ExConfig --version 2.0.0.1
                    
NuGet\Install-Package RuoVea.ExConfig -Version 2.0.0.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="RuoVea.ExConfig" Version="2.0.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RuoVea.ExConfig" Version="2.0.0.1" />
                    
Directory.Packages.props
<PackageReference Include="RuoVea.ExConfig" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add RuoVea.ExConfig --version 2.0.0.1
                    
#r "nuget: RuoVea.ExConfig, 2.0.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package RuoVea.ExConfig@2.0.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=RuoVea.ExConfig&version=2.0.0.1
                    
Install as a Cake Addin
#tool nuget:?package=RuoVea.ExConfig&version=2.0.0.1
                    
Install as a Cake Tool

📋 RuoVea.ExConfig

零依赖注入的静态配置读取器 — 提供 AppSettings 与 ConfigUtil 两大静态工具类,自动扫描多目录配置文件、环境感知加载、支持 JSON/XML/INI 格式,无需注册 DI 即可在任何位置读取配置。


📖 目录


📋 概览

RuoVea.ExConfig 为 .NET 开发者提供了一套完全静态的配置读取方案,无需在 Startup 或 Program.cs 中进行任何 DI 注册,即可在任何位置直接读取配置。

 ┌──────────────────────────────────────────────────┐
 │              RuoVea.ExConfig                      │
 ├──────────────────────────────────────────────────┤
 │  AppSettings (静态类)                              │
 │  ├─ app()              读取配置值(string/List<T>) │
 │  ├─ GetSection()       获取配置节                  │
 │  ├─ GetValue()         获取原始值                  │
 │  ├─ GetConfig<T>()     绑定强类型对象 + PostConfigure│
 │  ├─ GetAppSettings<T>() 绑定 class 配置             │
 │  ├─ ConnectionStrings() 读取连接字符串              │
 │  └─ append()           动态追加 JSON 节点           │
 │                                                   │
 │  ConfigUtil (静态类)                               │
 │  ├─ GetConfiguration   获取 IConfiguration         │
 │  ├─ GetSection()       获取配置节                  │
 │  ├─ GetConnectionString() 读取连接字符串            │
 │  ├─ GetJsonConfig()    加载 JSON 配置文件           │
 │  ├─ GetXmlConfig()     加载 XML 配置文件            │
 │  └─ GetIniConfig()     加载 INI 配置文件            │
 │                                                   │
 │  配置选项                                          │
 │  ├─ ConfigSettingsOptions  扫描目录/忽略目录配置    │
 │  └─ IConfigurableOptions  PostConfigure 标记接口   │
 ├──────────────────────────────────────────────────┤
 │  框架依赖: Microsoft.AspNetCore.App               │
 │  配置源: JSON | XML | INI | 环境变量 | 命令行参数  │
 └──────────────────────────────────────────────────┘

设计原则

原则 说明
零 DI 启动 所有方法均为 static,无需 IServiceProvider、无需 IOptions<T>
多源自动扫描 静态构造函数自动扫描 ConfigurationFiles/、Configuration/、Config/ 等目录
环境感知 自动读取 ASPNETCORE_ENVIRONMENT,优先加载 {name}.{env}.json
热重载 所有 JSON 文件均启用 reloadOnChange: true,修改配置文件即时生效
多格式支持 内置 JSON / XML / INI 三种配置源加载器
链式覆盖 加载顺序:JSON 文件 → 环境变量 → 命令行参数,后者覆盖前者

目标框架支持

TFM 包版本线 适用场景
netstandard2.0 2.0.x .NET Framework 4.6.2+ / .NET Core 3.0+ / .NET 5–10
netstandard2.1 2.1.x 仅 RuoVea.ExSugar:.NET Core 3.0+ / .NET 5–10(官方 ns2.1 版 ORM)
net8.0 8.0.x .NET 8/9(原生 ASP.NET Core 8 资产)
net10.0 10.0.x .NET 10(原生 ASP.NET Core 10 资产)

📦 安装

.NET CLI

# .NET Framework 4.6.2+ / .NET Core 3.0+ / .NET 5-10(netstandard2.0)
dotnet add package RuoVea.ExConfig --version 2.0.0.1

# .NET 8.0
dotnet add package RuoVea.ExConfig --version 8.0.0.1

# .NET 10.0
dotnet add package RuoVea.ExConfig --version 10.0.0.1

Package Manager

Install-Package RuoVea.ExConfig -Version 8.0.0.1

PackageReference

<PackageReference Include="RuoVea.ExConfig" Version="8.0.0.1" />

支持的 Target Framework

TFM 最低版本
net8.0 8.0.0.1
net10.0 10.0.0.1

依赖项

包名 版本 (net8.0) 版本 (net10.0)
Microsoft.AspNetCore.App FrameworkReference FrameworkReference
Microsoft.Extensions.Configuration.Json 8.0.0 10.0.8
Microsoft.Extensions.Configuration.Ini 8.0.0 10.0.8
Microsoft.Extensions.Configuration.Xml 8.0.0 10.0.8
Microsoft.Extensions.DependencyInjection.Abstractions 8.0.0 10.0.8
Microsoft.Extensions.FileProviders.Physical 8.0.0 10.0.8
Microsoft.Extensions.Options 8.0.0 10.0.8

⚠️ 注意: 该包依赖 Microsoft.AspNetCore.App 框架引用。在非 ASP.NET Core 项目(如控制台应用)中使用时,需确保 SDK 支持此框架引用,或手动添加对应包。


⚡ 30 秒快速开始

1. 导入命名空间

using RuoVea.ExConfig;                    // AppSettings, ConfigUtil, IConfigurableOptions
using RuoVea.ExConfig.Options;            // ConfigSettingsOptions

2. 第一行配置读取代码

// <inheritdoc cref="AppSettings.app(string[])"/>
// 读取 appsettings.json 中的 Logging:LogLevel:Default 节点
string logLevel = AppSettings.app("Logging", "LogLevel", "Default");
Console.WriteLine(logLevel); // "Information"

3. 绑定强类型配置

// <inheritdoc cref="AppSettings.GetConfig{T}(string, bool)"/>
// 假设 appsettings.json 中有如下节点:
// "EmailSettings": { "SmtpHost": "smtp.example.com", "Port": 587 }

var emailConfig = AppSettings.GetConfig<EmailSettings>("EmailSettings");
Console.WriteLine(emailConfig.SmtpHost); // "smtp.example.com"

30 秒内你完成了: 命名空间导入 → 读取嵌套配置值 → 绑定强类型配置对象。


🧩 核心场景

场景一:读取简单配置值

┌──────────────────────┐     app("A", "B", "C")     ┌──────────────┐
│  appsettings.json     │ ────────────────────────▶  │  配置值       │
│  { "A": { "B":        │                            │  (string)     │
│      { "C": "val" }}} │                            └──────────────┘
└──────────────────────┘
// <inheritdoc cref="AppSettings.app(string[])"/>
// 读取嵌套节点:用冒号连接各层级 Key
string value = AppSettings.app("ConnectionStrings", "DefaultConnection");
// 等价于 configuration["ConnectionStrings:DefaultConnection"]

// 读取顶层配置
string appName = AppSettings.app("AppName");

// 节点不存在时返回 ""(空字符串),不抛异常
string missing = AppSettings.app("NonExistent", "Key");
// missing == ""
读取列表类型配置
// <inheritdoc cref="AppSettings.app{T}(string[])"/>
// 读取基本类型列表(string、int 等)
List<string> allowedHosts = AppSettings.app<string>("AllowedHosts");

// 读取复杂对象列表
// appsettings.json:
// "Servers": [
//   { "Host": "srv1", "Port": 8080 },
//   { "Host": "srv2", "Port": 8081 }
// ]
List<ServerInfo> servers = AppSettings.app<ServerInfo>("Servers");
foreach (var srv in servers)
    Console.WriteLine($"{srv.Host}:{srv.Port}");

⚠️ 注意: app<T>(params string[]) 内部依据 typeof(T).IsPrimitive 判断是否走 Convert.ChangeType 还是 Configuration.Bind。对于 string 和 decimal 类型也会走基本类型路径,返回包含单个元素的 List<T>。


场景二:绑定强类型配置对象

┌──────────────────────┐   GetConfig<MyOptions>("Section")   ┌──────────────┐
│  appsettings.json     │ ────────────────────────────────▶  │  MyOptions   │
│  "Section": { ... }   │                                    │  实例         │
└──────────────────────┘                                    └──────────────┘
GetConfig<T> — 主推方式
// <inheritdoc cref="AppSettings.GetConfig{T}(string, bool)"/>
// 定义配置类
public class RedisOptions
{
    public string Host { get; set; } = "localhost";
    public int Port { get; set; } = 6379;
    public int Database { get; set; } = 0;
}

// 读取并绑定
var redis = AppSettings.GetConfig<RedisOptions>("Redis");
Console.WriteLine($"{redis.Host}:{redis.Port}");

// 启用 PostConfigure 后置处理
var redis2 = AppSettings.GetConfig<RedisOptions>("Redis", loadPostConfigure: true);
GetAppSettings<T> — 适用于 class 约束
// <inheritdoc cref="AppSettings.GetAppSettings{T}(string)"/>
// 泛型约束 where T : class, new()
var dbConfig = AppSettings.GetAppSettings<DatabaseConfig>("Database");
// dbConfig 为 null 如果节点不存在
GetValue — 获取原始值
// <inheritdoc cref="AppSettings.GetValue(string[])"/>
object raw = AppSettings.GetValue("Logging", "LogLevel", "Default");
// raw: "Information" (类型为 string)
GetSection — 获取配置节
// <inheritdoc cref="AppSettings.GetSection(string)"/>
IConfigurationSection section = AppSettings.GetSection("EmailSettings");
var children = section.GetChildren();

场景三:读取连接字符串

// <inheritdoc cref="AppSettings.ConnectionStrings(string, string)"/>
// 读取默认 "ConnectionStrings" 节点下的连接字符串
string connStr = AppSettings.ConnectionStrings("DefaultConnection");
// 等价于 configuration["ConnectionStrings:DefaultConnection"]

// 自定义根 Key 名称(如读取 "DbConnections" 节点下)
string connStr2 = AppSettings.ConnectionStrings("MyDb", rootKeyName: "DbConnections");
// <inheritdoc cref="ConfigUtil.GetConnectionString(string)"/>
// ConfigUtil 同样支持连接字符串读取
string connStr3 = ConfigUtil.GetConnectionString("DefaultConnection");

场景四:加载 JSON/XML/INI 配置文件

┌─────────────────┐                           ┌─────────────────┐
│  ConfigUtil      │  GetJsonConfig(file)      │  IConfiguration  │
│  GetXmlConfig()  │ ──────────────────────▶   │  Root            │
│  GetIniConfig()  │                           │                  │
└─────────────────┘                           └─────────────────┘
// <inheritdoc cref="ConfigUtil.GetJsonConfig(string, string)"/>
// 加载指定 JSON 配置文件
IConfigurationRoot jsonConfig = ConfigUtil.GetJsonConfig(
    configFileName: "mysettings.json",
    basePath: "ConfigFiles"
);

// <inheritdoc cref="ConfigUtil.GetXmlConfig(string, string)"/>
// 加载 XML 配置文件
IConfigurationRoot xmlConfig = ConfigUtil.GetXmlConfig(
    configFileName: "appsettings.xml",
    basePath: ""
);
// 打印 XML 配置中的所有值
foreach (var kv in xmlConfig.AsEnumerable())
    Console.WriteLine($"{kv.Key} = {kv.Value}");

// <inheritdoc cref="ConfigUtil.GetIniConfig(string, string)"/>
// 加载 INI 配置文件
IConfigurationRoot iniConfig = ConfigUtil.GetIniConfig(
    configFileName: "appsettings.ini",
    basePath: ""
);

❗ 路径注意: basePath 为空时默认为 Directory.GetCurrentDirectory()。在 ASP.NET Core 应用中,工作目录通常是项目根目录而非 bin/ 输出目录。AppSettings 的静态构造函数使用 AppContext.BaseDirectory(即 bin/ 目录),而 ConfigUtil 的方法默认使用 Directory.GetCurrentDirectory(),两者行为不同,混用时需注意。


场景五:自动扫描多目录配置

AppSettings 的静态构造函数会自动扫描以下目录中的 JSON 配置文件:

项目输出目录 (AppContext.BaseDirectory)
├── appsettings.json              ← 自动排除
├── appsettings.Development.json  ← 自动排除
├── emailsettings.json            ← ✅ 加载
├── emailsettings.Development.json ← ✅ 加载(环境匹配时)
├── ConfigurationFiles/           ← ✅ 扫描目录
│   └── thirdparty.json
├── Configuration/                ← ✅ 扫描目录
│   └── database.json
├── Config/                       ← ✅ 扫描目录
│   └── cache.json
└── ScanDirectories/              ← ✅ 扫描目录(自定义)
    └── business.json

自动排除规则:

  • 以 appsettings 开头的文件
  • bundleconfig / compilerconfig 文件
  • deps.json / runtimeconfig.json / runtimeconfig.dev.json / runtimeconfig.prod.json
  • 位于 IgnoreConfigurationFiles/ / IgnoreConfiguration/ / IgnoreConfig/ / IgnoreDirectories/ 目录中的文件

分组加载规则:

文件按名称前缀分组,每组加载两个文件({name}.json 优先,然后 {name}.{env}.json):

emailsettings.json                  ← 先加载(基础配置)
emailsettings.Development.json      ← 后加载(环境覆盖)

这种加载顺序确保了环境特定配置可以覆盖基础配置。


场景六:PostConfigure 后置配置

┌──────────────┐   GetConfig<T>(path, true)   ┌────────────────────┐
│  IConfigurable│ ─────────────────────────▶  │  PostConfigure()   │
│  Options     │                               │  通过反射调用        │
│  (标记接口)   │                               │  可修改绑定后的对象  │
└──────────────┘                               └────────────────────┘
// <inheritdoc cref="IConfigurableOptions"/>
// 1. 实现标记接口
public class AdvancedOptions : IConfigurableOptions
{
    public string? ApiBaseUrl { get; set; }
    public string? ApiKey { get; set; }
    public string? FullApiUrl { get; private set; }

    // 2. 定义 PostConfigure 方法(约定名,通过反射调用)
    public void PostConfigure(AdvancedOptions options, IConfiguration configuration)
    {
        // 在绑定完成后进行后置处理
        options.FullApiUrl = $"{options.ApiBaseUrl}/v2?key={options.ApiKey}";
    }
}

// 3. 启用 loadPostConfigure 参数
var advanced = AppSettings.GetConfig<AdvancedOptions>("ExternalApi", loadPostConfigure: true);
Console.WriteLine(advanced.FullApiUrl); // "https://api.example.com/v2?key=sk-xxx"

⚠️ 实现要求: PostConfigure 方法签名必须为 void PostConfigure(T options, IConfiguration configuration),框架通过 typeof(T).GetMethod("PostConfigure") 反射查找。若方法名或签名不匹配,后置处理将被静默跳过。

❗ 性能陷阱: GetConfig<T>(path, true) 通过反射调用 PostConfigure,且每次调用都会执行 GetMethod 查找(无缓存)。对于高频读取的配置,建议在应用启动时调用一次并缓存结果,而非在热路径上启用 loadPostConfigure。


场景七:动态追加 JSON 节点

// <inheritdoc cref="AppSettings.append(string, string)"/>
// 向 appsettings.json 动态追加 JSON 节点
string newConfig = @"""NewFeature"": {
    ""Enabled"": true,
    ""MaxRetry"": 3
}";
bool success = AppSettings.append(newConfig);

// 追加到自定义文件
bool success2 = AppSettings.append(newConfig, defultFile: "customsettings.json");

❗ 严重警告 — HACK 方法: append() 使用字符串拼接操纵 JSON 文件:

  1. 通过 ReadToEnd() 读取整个文件内容
  2. 查找最后一个 } 字符位置
  3. 用字符串拼接方式插入新节点(bodyValue.Substring(0, index-1) + ",\r\n" + jsonStr + "\r\n }")
  4. 直接覆盖写入原文件(FileMode.Open 截断写入)

已知风险:

  • 文件损坏风险:若 JSON 最后一个 } 不是根对象的闭合括号(如 JSON 中包含嵌套对象、字符串中包含 }),会导致 JSON 结构损坏
  • 并发安全:无文件锁保护,多线程/多进程同时写入会丢失数据或损坏文件
  • 无备份机制:写入失败后原始文件已损坏,无法回滚
  • 线程安全:无任何同步机制保护文件读写操作

建议替代方案:修改配置后使用 File.WriteAllText + System.Text.Json 序列化完整对象,或使用支持原子写入的配置存储方案。


⚙️ 自动扫描机制详解

初始化流程

AppSettings 静态构造函数
│
├─ 1. 读取 ASPNETCORE_ENVIRONMENT 环境变量
│
├─ 2. 创建 ConfigSettingsOptions(内置默认值)
│     ├─ ScanDirectories: [ConfigurationFiles, Configuration, Config, ScanDirectories]
│     └─ IgnoreConfigurationFiles: [IgnoreConfigurationFiles, IgnoreConfiguration,
│                                    IgnoreConfig, IgnoreDirectories]
│
├─ 3. 检查扫描目录是否存在(Directory.Exists)
│     只有物理存在的目录才会被扫描
│
├─ 4. 收集所有 *.json 文件(TopDirectoryOnly)
│
├─ 5. 过滤文件
│     ├─ 排除: appsettings*, bundleconfig, compilerconfig
│     ├─ 排除: deps.json, runtimeconfig*.json
│     └─ 排除: 位于忽略目录中的文件
│
├─ 6. 按名称前缀分组
│     ├─ {name}.json          ← 先加载
│     └─ {name}.{env}.json    ← 后加载(覆盖)
│
├─ 7. 添加配置源(按优先级,后者覆盖前者)
│     ├─ JSON 文件(reloadOnChange: true)
│     ├─ 环境变量(AddEnvironmentVariables)
│     ├─ 自定义 Action<IConfigurationBuilder>
│     └─ 命令行参数(AddCommandLine)
│
└─ 8. configurationBuilder.Build() → 赋值给 static Configuration

配置覆盖优先级(从低到高)

JSON 基础文件 ({name}.json)
  ↓ 覆盖
JSON 环境文件 ({name}.{env}.json)
  ↓ 覆盖
环境变量 (Environment Variables)
  ↓ 覆盖
命令行参数 (Command Line Args)

重新初始化配置

// <inheritdoc cref="AppSettings.AppSettings(Action{IConfigurationBuilder})"/>
// 实例化 AppSettings 会触发重新初始化 Configuration
var _ = new AppSettings(builder =>
{
    // 自定义配置源
    builder.AddJsonFile("override.json", optional: true, reloadOnChange: true);

    // 添加内存配置
    builder.AddInMemoryCollection(new Dictionary<string, string?>
    {
        ["Runtime:StartTime"] = DateTime.UtcNow.ToString("O")
    });
});

// 此后 AppSettings.Configuration 即包含自定义配置源

⚠️ 注意: new AppSettings(builder) 会完全重建 Configuration 静态字段,覆盖静态构造函数中的初始化结果。由于无锁保护,在并发环境中重新初始化可能导致其他线程读到中间状态的配置。


🛡️ 错误处理与日志

静默失败策略

AppSettings 的大多数方法在异常时不会抛出,而是返回默认值并输出 Console.WriteLine:

// <inheritdoc>
// app() — 异常时返回 ""
string value = AppSettings.app("NonExistent", "Key");
// → 控制台输出: "节点 NonExistent:Key 在 appsettings.json 中不存在"
// → 返回: ""

// <inheritdoc>
// GetValue() — 异常时返回 default
object result = AppSettings.GetValue("BadKey");
// → 返回: null

// <inheritdoc>
// append() — 异常时返回 false
bool ok = AppSettings.append(@"""Malformed"": }");
// → 控制台输出: "添加节点失败"
// → 返回: false

推荐日志模式

// <inheritdoc>
using Microsoft.Extensions.Logging;

public class ConfigurationService
{
    private readonly ILogger<ConfigurationService> _logger;

    public ConfigurationService(ILogger<ConfigurationService> logger) => _logger = logger;

    public T? GetConfigSafe<T>(string path) where T : class
    {
        try
        {
            var config = AppSettings.GetConfig<T>(path);
            if (config == null)
                _logger.LogWarning("配置节点 {Path} 不存在或绑定失败", path);
            return config;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "读取配置节点 {Path} 时发生未预期异常", path);
            return null;
        }
    }

    public string GetValueSafe(params string[] sections)
    {
        var key = string.Join(":", sections);
        var value = AppSettings.GetValue(sections);
        if (value == null)
            _logger.LogDebug("配置键 {Key} 未设置,使用默认值", key);
        return value?.ToString() ?? string.Empty;
    }
}

ConfigUtil 行为差异

ConfigUtil 的方法行为与 AppSettings 不同:

// GetConfiguration — 懒加载(首次访问时构建)
// 若 appsettings.json 不存在于 AppContext.BaseDirectory,构建可能失败或返回空配置

// GetConnectionString — 若 _config 为 null 返回 null
string? conn = ConfigUtil.GetConnectionString("Default");
// 可能返回 null

// GetSection — 若 _config 为 null 返回 null
var section = ConfigUtil.GetSection("Test");
// section 可能为 null,调用方需判空

🧵 线程安全

组件 线程安全 说明
AppSettings.Configuration (读) ✅ 是 IConfiguration / IConfigurationRoot 只读访问线程安全
AppSettings.Configuration (写) ⚠️ 否 公开 setter,无锁保护,并发重赋值存在竞态
AppSettings.app() ✅ 是 纯读取操作
AppSettings.GetConfig<T>() ✅ 是 读取操作线程安全;若 loadPostConfigure=true,每次反射调用无缓存但无状态共享
AppSettings.GetValue() ✅ 是 纯读取操作
AppSettings.ConnectionStrings() ✅ 是 纯读取操作
AppSettings.append() ❌ 否 文件读写无锁保护,多线程调用会导致数据损坏
new AppSettings(builder) ❌ 否 重建 Configuration 无锁,并发访问可能读到中间态
ConfigUtil.GetConfiguration (get) ⚠️ 否 懒初始化 _config 无锁(良性竞态 — 多次构建最终一致但浪费资源)
ConfigUtil.GetConfiguration (set) ✅ 是 引用类型赋值在 .NET 中是原子的
ConfigUtil.GetJsonConfig() ✅ 是 每次构建新实例,无共享状态
ConfigUtil.GetXmlConfig() ✅ 是 同 GetJsonConfig
ConfigUtil.GetIniConfig() ✅ 是 同 GetJsonConfig
ConfigSettingsOptions ✅ 是 仅含自动属性,无可变共享状态

⚠️ 重要: 在多线程环境中对 AppSettings.Configuration 重新赋值(通过 new AppSettings(builder)),正在读取的其他线程可能获取到部分构建的配置。建议在应用启动时完成所有配置初始化,运行期间仅读取。

// 推荐的线程安全初始化模式
public static class AppConfiguration
{
    private static readonly object _lock = new();
    private static IConfiguration? _configuration;

    public static IConfiguration Configuration
    {
        get
        {
            if (_configuration == null)
            {
                lock (_lock)
                {
                    _configuration ??= new ConfigurationBuilder()
                        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                        .AddEnvironmentVariables()
                        .Build();
                }
            }
            return _configuration;
        }
    }
}

📊 API 速查表

AppSettings

方法 签名 返回值 用途
app (params string[] sections) string 读取冒号分隔的嵌套配置值,不存在返回 ""
app<T> (params string[] sections) List<T> 绑定配置节点为列表(基本类型走 Convert.ChangeType,复杂类型走 Bind)
GetSection (string key) IConfigurationSection 获取指定 Key 的配置节
GetValue (params string[] sections) object 获取原始配置值,不存在返回 default
GetConfig<T> (string path, bool loadPostConfigure) T 绑定强类型配置对象,可选 PostConfigure 后置处理
GetAppSettings<T> (string key) where T : class, new() T? 绑定 class 配置对象
ConnectionStrings (string keyName, string rootKeyName) string? 读取连接字符串
append (string jsonStr, string defultFile) bool ⚠️ 字符串拼接追加 JSON 节点(高风险)

ConfigUtil

方法 签名 返回值 用途
GetConfiguration (prop) — IConfiguration 懒加载获取 appsettings.json 配置
GetConnectionString (string key) string? 读取连接字符串
GetSection (string key) IConfigurationSection? 获取配置节
GetJsonConfig (string fileName, string basePath) IConfigurationRoot 构建指定 JSON 文件配置
GetXmlConfig (string fileName, string basePath) IConfigurationRoot 构建指定 XML 文件配置
GetIniConfig (string fileName, string basePath) IConfigurationRoot 构建指定 INI 文件配置

选项类

类型 说明
ConfigSettingsOptions POCO 选项类,定义扫描目录和忽略目录(注意:AppSettings 内部硬编码了默认值,未消费此选项类)
IConfigurableOptions 标记接口,实现此接口的类可通过 PostConfigure 约定方法在配置绑定后执行后置处理

🗺️ 版本迁移指南

从 ConfigurationBuilder 手动代码迁移

旧代码模式 迁移到 RuoVea.ExConfig
new ConfigurationBuilder().SetBasePath(...).AddJsonFile(...).Build() AppSettings.Configuration 或 ConfigUtil.GetConfiguration
configuration.GetSection("X").Get<T>() AppSettings.GetConfig<T>("X")
configuration.GetConnectionString("Default") AppSettings.ConnectionStrings("Default")
configuration["A:B:C"] AppSettings.app("A", "B", "C")
configuration.GetSection("X").Bind(list) AppSettings.app<T>("X")

从 IOptions<T> 模式迁移

// 旧模式(需要 DI 注册)
// services.Configure<MyOptions>(configuration.GetSection("MyOptions"));
// var opts = serviceProvider.GetRequiredService<IOptions<MyOptions>>().Value;

// 新模式(零 DI)
var opts = AppSettings.GetConfig<MyOptions>("MyOptions");

v8.0.x → v10.0.x

  • API 无变化。v10.0.x 仅在 net10.0 TFM 上编译,所有公开 API 签名保持一致。
  • 依赖包版本从 8.0.0 升级至 10.0.8,但 API 表面保持一致。

📄 License

MIT License © RuoVea


🔗 相关资源: NuGet Gallery · 问题反馈

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (11)

Showing the top 5 NuGet packages that depend on RuoVea.ExConfig:

Package Downloads
RuoVea.ExFilter

注入 进行全局的异常日志收集、执行操作日志、参数验证,支持简体中文、繁体中文、粤语、日语、法语、英语.services.ExceptionSetup();// 注入 全局错误日志处 services.ExceptionSetup(ExceptionLog actionOptions);// 注入 全局错误日志处 services.ExceptionSetup(builder.Configuration.GetSection("AopOption:ExceptionLog"));// 注入 全局错误日志处 services.RequestActionSetup();// 注入 请求日志拦截 [执行操作日志、参数验证 ] services.RequestActionSetup(RequestLog actionOptions);// 注入 请求日志拦截 [执行操作日志、参数验证 ] services.RequestActionSetup(builder.Configuration.GetSection("AopOption:RequestLog"));// 注入 请求日志拦截 [执行操作日志、参数验证 ] services.ResourceSetup();//对资源型信息进行过滤 services.ResultSetup();//对结果进行统一 services.ApISafeSetup(AppSign actionOptions);//接口安全校验 services.ApISafeSetup(builder.Configuration.GetSection("AopOption:AppSign"));//接口安全校验 services.ApISignSetup(AppSign actionOptions);//签名验证 ( appKey + signKey + timeStamp + data ); services.ApISignSetup(builder.Configuration.GetSection("AopOption:AppSign"));//签名验证 ( appKey + signKey + timeStamp + data ); services.AddValidateSetup();//模型校验 services.AddUiFilesZipSetup();//将前端UI压缩文件进行解压 不进行接口安全校验 -> NonAplSafeAttribute 不签名验证 -> NonAplSignAttribute 不进行全局的异常日志收集 -> NonExceptionAttribute 不对资源型信息进行过滤 -> NonResourceAttribute 不对结果进行统一 -> NonRestfulResultAttribute

RuoVea.ExCache

Redis缓存 内存缓存

RuoVea.ExJwtBearer

Jwt 授权验证拓展插件。声名:IJwtHelper _jwtHelper,支持简体中文、繁体中文、粤语、日语、法语、英语.添加验权:services.AddAuthenticationSetup(enableGlobalAuthorize: true);添加鉴权:services.AddAuthorizationSetup.MyPermission.(enableGlobalAuthorize: true);添加Jwt加密:services.AddJwtSetup();

RuoVea.OmiApi.SystemApp

系统应用管理

RuoVea.OmiApi.UserRoleMenu

用户角色菜单管理

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.0.0.1 3,399 5/28/2026
10.0.0 584 1/12/2026
9.0.0 2,076 7/25/2025
8.0.0.1 15,004 4/23/2025
8.0.0 2,200 3/12/2024
7.0.0.1 10,500 4/23/2025
7.0.0 2,486 3/12/2024
6.0.1.7 13,168 4/23/2025
6.0.1.6 10,341 3/12/2024
6.0.1.5 322 3/12/2024
6.0.1.4 323 3/12/2024
6.0.1.3 932 1/26/2024
6.0.1.2 326 1/26/2024
6.0.1.1 1,102 11/19/2023
6.0.1 6,136 2/16/2022
6.0.0 5,229 2/9/2022
5.0.19.2 1,465 4/23/2025
5.0.19.1 829 8/28/2024
5.0.19 1,087 3/22/2022
2.0.0.1 192 11/12/2026
Loading failed