Liwendong.Utility 3.2.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Liwendong.Utility --version 3.2.0
                    
NuGet\Install-Package Liwendong.Utility -Version 3.2.0
                    
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="Liwendong.Utility" Version="3.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Liwendong.Utility" Version="3.2.0" />
                    
Directory.Packages.props
<PackageReference Include="Liwendong.Utility" />
                    
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 Liwendong.Utility --version 3.2.0
                    
#r "nuget: Liwendong.Utility, 3.2.0"
                    
#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 Liwendong.Utility@3.2.0
                    
#: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=Liwendong.Utility&version=3.2.0
                    
Install as a Cake Addin
#tool nuget:?package=Liwendong.Utility&version=3.2.0
                    
Install as a Cake Tool

Liwendong.Utility

通用辅助工具集合,一个包覆盖 .NET Framework 老项目到 .NET 8 新项目。

支持的目标框架

目标框架 说明
net8.0 主要开发与推荐目标
netcoreapp3.1 维护中的存量项目
net46 .NET Framework 4.6
net451 .NET Framework 4.5.1

多框架差异通过条件编译处理,同一份调用代码在四个框架下均可编译。 已知的平台相关限制见下方「平台与多版本注意事项」。

安装

dotnet add package Liwendong.Utility

工具类一览

类别 类 说明
配置 ConfigHelper 统一读取配置(Core 读 appsettings.json,Framework 读 App.config)
缓存 CacheHelper 内存缓存(Core 用 IMemoryCache,Framework 用 MemoryCache)
JSON JsonHelper 序列化 / 反序列化 / JSONPath 取值 / 深拷贝
加密 SecurityHelper MD5、SHA、HMAC、DES、AES、RSA、Base64、PBKDF2、AES-GCM
证书 CertHelper X509 证书读取与导出
HTTP HttpHelper 基于 HttpWebRequest 的同步请求(含回调式异步)
HTTP HttpClientHelper 推荐,基于 HttpClient 的 Task 异步请求,支持 CancellationToken
字符串 StringHelper 字符串处理与扩展
转换 ConvertHelper 类型转换
编码 EncodingHelper 编码识别与转换
正则 RegexHelper 常用正则常量与匹配/提取/替换
压缩 CompressHelper GZip、Deflate、ZIP
网络 IpHelper IP 校验、内外网判断、整数互转
图片 ImageHelper 图片处理(仅 Windows)
条码 BarCodeHelper Code128 一维码(仅 Windows)
日志 LogHelper 文件日志
IO IOHelper 文件与目录操作
反射 ReflectionHelper 程序集与类型扫描
时间 DateTimeHelper 日期时间处理
随机 RandomHelper 随机数与随机字符串
ID Snowflake 雪花算法分布式 ID
邮件 EmailHelper SMTP 邮件发送(SmtpClient / MailKit 双实现)
线程 ThreadingHelper 线程池与 Mutex
XML XmlHelper XML 序列化与操作
Web WebHelper / CookieHelper / HtmlHelper Web 相关辅助
校验 ValidationHelper 基于 DataAnnotations 的模型校验
签名 ApiHelper 接口签名生成与校验

使用示例

配置读取(无配置文件也不会崩)

// 缺少 appsettings.json 时返回默认值,不抛异常(net451 与 net8.0 行为一致)
var size = ConfigHelper.GetValue("LogFileMaxSize", 2M);
var conn = ConfigHelper.GetConnectionStrings<string>("Default");

// 可判断配置是否真的加载成功
if (!ConfigHelper.HasConfiguration)
{
    // 输出诊断信息
}

异步 HTTP 请求

// HttpClientHelper:Task-based 异步,支持取消
var json = await HttpClientHelper.GetStringAsync(url, cancellationToken: cts.Token);
var model = await HttpClientHelper.GetJsonAsync<MyModel>(url);
var result = await HttpClientHelper.PostJsonAsync(url, new { name = "test" });

// HttpHelper 的异步重载
var info = await HttpHelper.GetAsync(url, "a=1");

缓存

CacheHelper.Set("key", value);                          // 默认滑动过期 20 分钟
var v = CacheHelper.GetOrAdd("key", () => LoadData());  // 不存在时自动生成

口令哈希与现代加密

var hash = SecurityHelper.HashPassword("mypassword");        // PBKDF2
bool ok = SecurityHelper.VerifyPassword("mypassword", hash);

// AES-256-GCM(仅 net5.0+,密文被篡改会返回 null)
var cipher = SecurityHelper.AesGcmEncrypt("secret", key);
var plain = SecurityHelper.AesGcmDecrypt(cipher, key);

邮件发送(MailKit,推荐)

// 1. 便捷异步:自动按发件人域名推断 SMTP(内置 163/qq/gmail/aliyun 等域名表)
var (ok, msg) = await EmailHelper.SendEmailAsync(
    toEmail:      "receiver@example.com",
    subject:      "订单通知",
    htmlBody:     "<h1>你好</h1>",
    fromEmail:    "sender@qq.com",
    password:     "授权码",
    attachments:  new[] { @"D:\report.xlsx" });

// 2. 完整控制:抄送、密送、纯文本备选、加密方式、超时、取消令牌
var message = new EmailMessage
{
    FromAddress = "sender@example.com",
    FromDisplayName = "系统通知",
    Subject = "中文主题不会乱码",
    HtmlBody = "<b>HTML 正文</b>",
    TextBody = "纯文本备选",
    Priority = MimeKit.MessagePriority.Urgent,
    AttachmentPaths = { @"D:\a.pdf" }
};
message.To.Add("a@example.com");
message.Cc.Add("b@example.com");
message.Bcc.Add("c@example.com");

var options = new SmtpOptions("smtp.example.com", "sender@example.com", "授权码", 587)
{
    SocketOptions = MailKit.Security.SecureSocketOptions.StartTls,
    Timeout = 30000
};

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var result = await EmailHelper.SendEmailAsync(message, options, cts.Token);

// 3. 同步版本(内部以线程池线程执行,不会因同步上下文死锁)
var sync = EmailHelper.SendEmailByMailKit(message, options);

新旧实现对比:

SendEmail(SmtpClient) SendEmailAsync / SendEmailByMailKit(MailKit)
异步 / 取消 不支持 原生 Task + CancellationToken
中文主题 需手动处理编码 标准 MIME 编码,不乱码
收件人 单个 收件人 / 抄送 / 密送 多个
附件 单个 多个
跨平台 Windows 行为有差异 各平台一致
维护状态 微软标记 SYSLIB0016 过时 官方推荐替代

SendEmail(基于 System.Net.Mail.SmtpClient)保留不变,现有代码无需迁移; 新代码建议使用 MailKit 版本。

JSON

var json = JsonHelper.Serialize(obj);
var obj  = JsonHelper.Deserialize<MyModel>(json);
var name = JsonHelper.GetValue(json, "data.list[0].name");

平台与多版本注意事项

  1. System.Drawing 仅 Windows:ImageHelper、BarCodeHelper、Gif/* 依赖 System.Drawing.Common,已标注 [SupportedOSPlatform("windows")]。 在 Linux / 容器环境调用会抛 PlatformNotSupportedException,请改用 ImageSharp / SkiaSharp。

  2. AES-GCM 仅 .NET 5+:SecurityHelper.AesGcmEncrypt/AesGcmDecrypt 在 net451/net46/netcoreapp3.1 下不参与编译。PBKDF2 全框架可用。

  3. X509Certificate2 的释放:该类型直到 .NET Framework 4.6 才实现 IDisposable, 因此 net451 下无法使用 using,库内部已按条件编译统一处理。

  4. 配置键的命名:netcore 下 GetAppSettings("X") 读取 AppSettings:X 节点, net451 下读取 App.config 的 <appSettings> 配置节,两者配置结构不同, 跨框架迁移时需注意。推荐使用 GetValue 配合统一的配置结构。

重要变更(V3.1.0)

  • 修复:ConfigHelper 在缺少 appsettings.json 时抛 TypeInitializationException, 导致控制台 / 类库 / 单元测试等非 ASP.NET 环境下整个类不可用,并连带使 LogHelper 静默失效。 现改为延迟构建 + 缺失时回退空配置。
  • 修复:ImageHelper.AddFontWaterMark 判空逻辑写反,调用方传入的水印文字被强制覆盖。
  • 修复:ApiHelper.VerifyRequestSignature 转发时漏传 vaildSeconds,导致时间戳有效期校验被忽略。
  • 修复:Snowflake 的状态字段误声明为 static,同进程多实例会互相覆盖产生重复 ID。
  • 修复:EmailHelper 默认端口误写为 578(修正为 587),并补齐资源释放。
  • 修复:CertHelper.GetPrivateKey / GetPrivateKeyFromStore 为半成品(前者丢弃结果,后者恒定返回空串)。
  • 更新:CertHelper 公钥 / 私钥读取改用 GetRSAPublicKey() / GetRSAPrivateKey() (PublicKey.Key、PrivateKey 已在 .NET 8 标记为 SYSLIB0027 / SYSLIB0028 过时)。 net451 无新 API,仍走旧路径;非 RSA 证书(如 DSA)自动回退旧路径,行为不变。
  • 安全:移除 CertHelper 中硬编码的默认加密串,以及 SecurityHelper 内置的 DES 默认密钥 liwen528(公开代码中硬编码密钥等同于明文)。未显式设置密钥时 DESEncrypt/DESDecrypt 会抛出明确异常。
  • 命名:EncodingHepler → EncodingHelper、ValidatetionHelper → ValidationHelper、 ASE_Encrypt/ASE_Decrypt → AES_Encrypt/AES_Decrypt、GetPlulicKey → GetPublicKey。 旧名称保留并标记 [Obsolete],现有代码仍可编译,建议尽快迁移。
  • 破坏性:ConfigHelper.GetEntity<T> 在 net451 下的泛型约束由 class, IConfigurationSectionHandler, new() 放宽为 class, new(),与 netcore 保持一致。
  • 新增:EmailHelper 增加基于 MailKit 的 SendEmailAsync / SendEmailByMailKit, 支持异步与取消令牌、多收件人、抄送与密送、多附件、显式加密策略与超时控制。 原 SendEmail(SmtpClient)保持不变,现有代码无需迁移。
  • 安全:SecurityHelper.HashPassword 文档声明为 PBKDF2-HMAC-SHA256, 但此前调用 Rfc2898DeriveBytes 三参数重载,实际使用的是 SHA1。 现改为自行实现 PBKDF2-HMAC-SHA256(已通过标准测试向量与 .NET 内置实现交叉验证)。 之所以不直接用带 HashAlgorithmName 的重载,是因为该重载在 net451/net46 上不存在, 按框架分档调用会导致同一口令在不同框架下哈希不同、换框架后存量口令全部校验失败。 哈希串格式相应升级为 版本.迭代次数.盐.哈希,旧的 3 段格式仍可校验通过。

更新日志

V3.1.*

  • [3.1.1] 新增基于 MailKit 的邮件发送(异步 / 取消令牌 / 抄送密送 / 多附件); 修正 HashPassword 实际使用 SHA1 与文档不符的问题,改为全平台一致的 PBKDF2-HMAC-SHA256; 修复 EncodingHelper.cs 中 1335 处中文注释乱码(2026-08-30 提交误将 GBK 按 UTF-8 转码所致)。
  • [3.1.0] 修复 ConfigHelper 跨版本崩溃链与多项缺陷;新增 JsonHelper / CacheHelper / CompressHelper / RegexHelper / IpHelper / HttpClientHelper;补充异步 API 与 CancellationToken; 新增 PBKDF2 与 AES-GCM;补全 README。

V3.0.*

  • [3.0.0] 支持 .NET 8.0
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 is compatible.  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 netcoreapp3.1 is compatible. 
.NET Framework net451 is compatible.  net452 was computed.  net46 is compatible.  net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (4)

Showing the top 4 NuGet packages that depend on Liwendong.Utility:

Package Downloads
Liwendong.Frameworks

基础框架

Liwendong.Frameworks.Services.API

服务API管理

Liwendong.Wexin.MP.SDK

微信公众号辅助SDK

Liwendong.Frameworks.Data.DapperExtend

Dapper扩展

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.3.3 160 10/23/2026
3.3.2 90 10/22/2026
3.3.1 334 10/20/2026
3.2.0 107 10/8/2026
2.9.3 274 5/9/2026
2.9.2 185 2/15/2026
2.9.1 352 11/27/2025
2.8.11 315 11/24/2025
2.8.10 755 11/20/2025
2.8.9 232 9/27/2025
2.8.8 430 9/22/2025
2.8.7 423 9/17/2025
2.8.6 339 9/15/2025
2.8.5 328 9/4/2025
2.8.3 840 9/1/2025
2.8.2 468 8/26/2025
2.8.1 252 8/23/2025
2.8.0 344 8/13/2025
2.7.3 299 8/13/2025
2.7.2 474 8/13/2025
Loading failed