XYS.Utils.Sys 2.8.0

dotnet add package XYS.Utils.Sys --version 2.8.0
                    
NuGet\Install-Package XYS.Utils.Sys -Version 2.8.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="XYS.Utils.Sys" Version="2.8.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="XYS.Utils.Sys" Version="2.8.0" />
                    
Directory.Packages.props
<PackageReference Include="XYS.Utils.Sys" />
                    
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 XYS.Utils.Sys --version 2.8.0
                    
#r "nuget: XYS.Utils.Sys, 2.8.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 XYS.Utils.Sys@2.8.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=XYS.Utils.Sys&version=2.8.0
                    
Install as a Cake Addin
#tool nuget:?package=XYS.Utils.Sys&version=2.8.0
                    
Install as a Cake Tool

XYS.Utils.Sys

系统级通用工具类库:HTTP/JSON 调用、文件、类型转换、反射、XML、邮件、CSV 导出、配置读取与加解密,以及数据库映射与 SQL 辅助等。

目标框架

net8.0 · net462 · netcoreapp3.1 · netstandard2.0 · netstandard2.1

依赖


HttpJsonUtil

基于 HttpClient 的 JSON 与表单请求工具,提供 POST / GET 并自动反序列化响应,支持 HTTPS。

using XYS.Utils.Sys;

// POST:对象自动序列化为 JSON,反序列化为任意指定类型(DTO、数组、集合、字符串等)
var res = HttpJsonUtil.Post<ResultDto>("https://api.example.com/order", new { id = 1 }, timeout: 5000);

// GET
var dto = HttpJsonUtil.Get<ResultDto>("https://api.example.com/order/1");

// 带 Cookie / 自定义 UserAgent(单次请求按需注入 Cookie 头,复用底层连接池且不串号)
var res2 = HttpJsonUtil.Post("https://api.example.com/x", req, timeout: 3000, userAgent: "MyApp", cookies: myCookies);

// 自定义请求头:全局默认头(启动时注入一次)
HttpJsonUtil.DefaultHeaderProvider = () => new Dictionary<string, string>
{
    ["X-Api-Key"] = "your-api-key",
};
// 或单次请求头(同名覆盖全局默认头,自动区分请求头与 Content-Type 等正文头),POST/GET 均支持
var res3 = HttpJsonUtil.Post<ResultDto>("https://api.example.com/x", req,
    headers: new Dictionary<string, string> { ["X-Request-Id"] = Guid.NewGuid().ToString() });

// 表单提交(multipart/form-data):服务端以表单字段接收,字段值本身可为 JSON 字符串
var res4 = HttpJsonUtil.PostForm<ResultDto>("https://api.example.com/gateway",
    new Dictionary<string, string>
    {
        ["interfaceName"] = "doctor",
        ["methodName"]    = "getPatientEmrContentById",
        ["data"]          = "{\"recordId\":\"xxx\",\"contentType\":\"html\"}",
    });
// 需要原始响应字符串时用同名非泛型重载:HttpJsonUtil.PostForm(url, fields)
  • HTTPS:静态构造时确保启用 TLS 1.2(兼容 net462 等旧框架访问现代 HTTPS 服务)。若进程当前为 SystemDefault(由操作系统协商,可含 TLS 1.3)则不改动,也不再追加已废弃的 TLS 1.1;.NET Core/5+ 由系统协商,无副作用。
  • 证书校验:HttpJsonUtil.AllowUntrustedCertificate 默认 false,执行标准 TLS 证书校验,防止中间人攻击。内网自签证书部署需在应用启动时显式置为 true。该开关只作用于 HttpJsonUtil 自己发出的请求;net462 下使用实例级回调(WebRequestHandler),不修改进程级 ServicePointManager.ServerCertificateValidationCallback。
  • 连接池与 DNS 刷新:共享客户端设定 5 分钟连接生命周期(SocketsHttpHandler.PooledConnectionLifetime / net462 ServicePoint.ConnectionLeaseTimeout),长驻进程可感知 DNS 变更;禁用共享 CookieContainer,单次 cookies 参数格式化为请求级 Cookie 头,既防跨请求串号又避免频繁创建/释放 HttpClient 耗尽端口。
  • 自定义请求头:全局 DefaultHeaderProvider + 各方法末尾的 headers 参数,同名覆盖;自动识别 Content-Type 等正文头写入 request.Content.Headers。
  • 泛型反序列化:Post<T> / PostForm<T> / Get<T> 不再限制 where T : new(),可直接反序列化为 string、数组、接口集合或含参构造记录类型。
  • 错误诊断:请求失败时异常携带状态码与响应体;超时抛出语义明确的 TimeoutException(含 URL 与毫秒数)。返回 SendResult/BaseRes 的重载在响应体为空时按错误返回(Code 为 ERR/error)。

需要按 baseUrl 复用客户端、请求级超时隔离与 Token 注入的高并发场景,参见 XYS.Utils.Web 中的 HttpRestUtil。


TypeExtension

常用类型扩展方法。

using XYS.Utils.Sys;

string json = anyObject.ToJson();                 // 序列化为 JSON
int? n = "123".ToInt();                            // 安全转 int?
DateTime? d = "2026-07-21".ToDateTime();           // 安全转 DateTime?(优先按固定格式+不变区域性解析)
string xml = raw.ToXmlStr();                        // XML 特殊字符转义

ToJson / ToInt / ToFloat / ToDouble / ToDecimal / ToDateTime / ToSmallDateTime / ToXmlStr 等,均对 null/空白/非法输入做安全处理。


FileUtil

文件与目录辅助:

  • File2Bytes(fullFileName) — 读取文件为字节数组(空路径或不存在返回 null)
  • GetFullName(params paths) — 拼接路径
  • MakeDir(filePath) — 创建目录
  • IsFileExist / IsDictExist / DeleteFile / DeleteDict

ConvertUtil

安全类型转换:TryParse 的 int / long / short 重载,转换失败返回 false 且不抛异常。按不变区域性直接解析目标类型,超过 $2^{53}$ 的长整型(如雪花 ID)不会丢失精度。


ReflexUtil

反射辅助:AssemblyShortName / AssemblyFileName / GetTypeFromString(按类型名解析 Type)。


XmlUtil

XML 辅助(默认禁用 DTD 与外部实体解析,防止 XXE):

  • Serialize<T>(obj) / DeSerialize<T>(xml) / ParseFromXml<T>(xml)(保留历史拼写兼容 ParseFormXml<T>) — 对象与 XML 字符串互转
  • GetData<T>(XmlNode) — 按属性名映射 XML 直接子元素到实体
  • TypeConvert(input, type) / DefaultForType(type) — 安全类型转换与类型默认值获取
  • Serialize<T>(obj, encoding) 传入带 BOM 的编码(如 Encoding.UTF8)时自动剥离前导 U+FEFF

MailHelper

邮件发送:支持同步 MailHelper.SendMail(MailRequest) 与异步 MailHelper.SendMailAsync(MailRequest, CancellationToken)。成功返回空字符串,失败返回包含内部原因链的错误信息。

SMTP 参数从 xys.config.json 的 appSettings 读取:

  • smtpServer / smtpServerPort — 服务器地址与端口
  • mailUser / mailUserPW — 认证账号密码(mailUserPW 支持 ENC(...) 密文)
  • defaultMailFrom — 默认发件人(支持分号/逗号分隔的多地址,首个作为 From,全部加入 ReplyToList)
  • smtpEnableSsl — 设为 true 或 1 时启用 SSL/TLS
  • smtpTimeout — 可选超时毫秒数

CSVUtil

CSV 导出:CSVUtil.ExportCSV(fileName, csvStrs, csvSeparator = ',', coding = null, sanitizeFormula = false)(旧版 ExportHelper.ExportCVS 已标记 [Obsolete] 并转发至本方法)。

  • 默认编码为 UTF-8(带 BOM),父目录不存在时自动创建。
  • 按 RFC 4180 转义;开启 sanitizeFormula: true 时对 =、+、-、@ 开头的文本前置单引号防范电子表格公式注入。

SystemInfo

配置读取与系统辅助(配置文件 xys.config.json,读取后缓存):

  • GetAppSetting(key) / GetConfigValue(key) — 读取配置项
  • GetConnString(name) / GetConnStruct(name) — 读取数据库连接串(透明支持 ENC(...) 解密)
  • ReloadConfig() — 重新加载配置
  • ToBoolean(value, default) — 支持 true/false 与 1/0(自动忽略首尾空白)
  • ProcessStartTime — 实际进程启动时间

DB(数据库映射与 SQL 辅助 —— 已由本库完全接管)

命名空间 XYS.Utils.DB 下的数据库辅助类现由 XYS.Utils.Sys 完全承接维护(原 XYS.Utils.DB 2.8.0+ 已改为纯 [TypeForwardedTo] 转发兼容层,彻底消除 CS0433 类型冲突):

  • DBUtil.Convert / DeConvert — 基于 DBColAttribute 的实体与数据源对象双向映射(内置反射元数据缓存,自动处理 DBNull、可空类型、枚举及跨数值转换)
  • DBHelper — 存储过程入/出参装配、DB 值与类型解析
  • DBParse — 安全取值(GetSafeInt / GetSafeDate / GetSafeDecimal / GetSafeStr 等),兼容 null、DBNull、跨数值类型及字符串转换,不抛动态绑定异常
  • NConvert — 数值/日期/布尔安全转换,含四位分节中文大写金额转换 ToCapital(支持 ±999,999,999,999.99)
  • SqlUtil.GetWhere(paramDict, tableAlias) — 由字典拼接 WHERE 条件:支持任意白名单元素类型的集合/数组(空集合生成 1=0),数值固定不变区域性,非法标识符或非白名单类型抛 ArgumentException

配置加密:Crypto

保护 xys.config.json 中的敏感值(如数据库连接串、SMTP 密码):

  • 算法:AES-256-CBC + HMAC-SHA256(Encrypt-then-MAC),全 5 个目标框架原生支持,无第三方依赖。
  • 密钥优先级:Crypto.SetKey(...) > 环境变量 XYS_CRYPTO_KEY > 内置默认密钥。
$env:XYS_ENC_INPUT = 'Server=db;User Id=app;Password=真实密码;'
dotnet test XYS.Utils.Sys.Tests --filter FullyQualifiedName~ConnStrEncryptTool

版本

当前版本 2.8.0。

2.8.0 变更

  • 完全接管 XYS.Utils.DB:XYS.Utils.DB 改造为 TypeForwardedTo 转发包,彻底消除双包共存时的 CS0433 编译冲突。
  • 随包生成 XML 注释文档:开启 GenerateDocumentationFile,下游 IDE 可直接查看完整中文智能提示。
  • NConvert.ToCapital 重构:修复亿级金额(如 100000000m)多拼单位及极小小数(如 0.001m)误返 "整" 的问题,消除区域性依赖;统一 NConvert 各方法对 DBNull/空白/非法输入的安全回退行为。
  • DBParse & DBUtil 健壮性与性能增强:DBParse 支持跨数值与字符串安全转换,不再抛 RuntimeBinderException;DBUtil 增加反射元数据缓存并兼容 DBNull、可空类型、枚举及只读属性。
  • SqlUtil.GetWhere 扩展:支持任意受支持元素类型的数组/集合(如 List<long>、int[]、HashSet<string>),并校验 SelectSql<T> 表名标识符。
  • HttpJsonUtil 优化:移除 Post<T>/Get<T>/PostForm<T> 的 where T : new() 限制;配置 5 分钟连接池轮换刷新 DNS;单次 cookies 改为请求头注入以复用连接池并防止跨请求串号;修复 Content-Type 等正文头覆盖与异常路径 HttpContent 释放。
  • MailHelper 增强:新增 SendMailAsync 异步发送、支持 smtpTimeout 与 smtpEnableSsl=1、兼容多发件人地址并附带内部异常详情。
  • XmlUtil / CSVUtil / SystemInfo 加固:XmlUtil 新增 ParseFromXml<T> 并禁用 DTD 防范 XXE;ExportHelper.ExportCVS 重命名为 CSVUtil.ExportCSV(原名标记 [Obsolete] 兼容转发,支持自动建目录与可选公式注入防护);Crypto 及时清零临时派生密钥缓冲。
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 netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 is compatible. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 is compatible.  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 (19)

Showing the top 5 NuGet packages that depend on XYS.Utils.Sys:

Package Downloads
XYS.FR

FastReport 数据契约与配置层:负责实体表结构注册、FRTables.frd 生成、流式模板与行列对照配置管理及导出/打印服务抽象契约。

XYS.DataFactory

Package Description

XYS.Utils.DB

Package Description

XYS.Mongo

Package Description

XYS.Lab.Mongo

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.8.0 99 11/29/2026
2.7.0 232 11/16/2026
2.6.0 386 7/25/2026
2.5.0 363 7/22/2026
2.3.3 230 7/21/2026
2.3.2 198 7/16/2026
2.3.1 236 7/14/2026
2.2.1.4 300 1/7/2026
2.2.1.2 921 12/7/2023
2.2.1.1 640 12/4/2023
2.1.2.1 602 11/24/2023
2.1.1.2 300 10/27/2023
2.1.1.1 593 5/15/2023
2.1.0.10 467 2/13/2023
2.1.0.9 604 2/8/2023
2.1.0.8 505 2/1/2023
2.1.0.7 500 2/1/2023
2.1.0.6 534 1/18/2023
2.1.0.5 532 1/18/2023
Loading failed