XYS.Utils.Sys 2.7.0

dotnet add package XYS.Utils.Sys --version 2.7.0
                    
NuGet\Install-Package XYS.Utils.Sys -Version 2.7.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.7.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.7.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.7.0
                    
#r "nuget: XYS.Utils.Sys, 2.7.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.7.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.7.0
                    
Install as a Cake Addin
#tool nuget:?package=XYS.Utils.Sys&version=2.7.0
                    
Install as a Cake Tool

XYS.Utils.Sys

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

目标框架

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

依赖


HttpJsonUtil

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

using XYS.Utils.Sys;

// POST:对象自动序列化为 JSON,反序列化为指定类型
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
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",
};
// 或单次请求头(同名覆盖全局默认头),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,不影响同进程的 SmtpClient、WCF 等。

    ⚠️ 默认值由 true 改为 false,属于行为变更:原先依赖自签证书的部署升级后需加一行 HttpJsonUtil.AllowUntrustedCertificate = true;。

  • 自定义请求头:全局 DefaultHeaderProvider + 各方法末尾的 headers 参数,内部 AddOrUpdateHeader 同名覆盖;Key 空或 Value 为 null 的项自动跳过。
  • 表单提交:PostForm<T> / PostForm(原始字符串重载)以 multipart/form-data 提交字段,适配「服务端以表单字段接收、字段值为 JSON 字符串」的统一网关类接口;字段 UTF-8 编码,Value 为 null 时按空串提交。
  • 错误诊断:请求失败时异常携带状态码与响应体;超时抛出语义明确的 TimeoutException(含 URL 与毫秒数)。返回 SendResult/BaseRes 的重载在响应体为空时也按错误返回(Code 为 ERR/error),不再返回 null。
  • timeout 单位毫秒,可超过 100 秒(HttpClient 自带的 100 秒上限已关闭,超时只由该参数决定)。无 Cookie 时复用静态 HttpClient;带 Cookie 时创建独立实例并自动释放。

需要按 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) — 读取文件为字节数组
  • 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 辅助:

  • Serialize<T>(obj) / DeSerialize<T>(xml) — 对象与 XML 字符串互转(序列化输出紧凑、抑制 xsi/xsd 命名空间声明)
  • GetData<T>(XmlNode) — 按属性名映射 XML 子节点到实体
  • TypeConvert(input, type) 按目标类型转换字符串,转换失败返回类型默认值(GetData 遇到非法值不再抛异常);DefaultForType(type) 返回类型默认值
  • Serialize<T>(obj, encoding) 传入带 BOM 的编码(如 Encoding.UTF8)时,返回的字符串不再以 U+FEFF 开头

MailHelper

邮件发送:MailHelper.SendMail(MailRequest request),MailRequest 支持正文、收件人及 MailRequestAttachments 附件。成功返回空字符串,失败返回错误信息。

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

  • smtpServer / smtpServerPort — 服务器地址与端口
  • mailUser / mailUserPW — 认证账号密码(留空则用默认网络凭据);mailUserPW 支持与连接串相同的 ENC(...) 密文,明文照常可用
  • defaultMailFrom — 默认发件人(MailRequest.From 为空时使用,不会回写到传入的 MailRequest)
  • smtpEnableSsl — 设为 true 时启用 SSL/TLS(适配 587/465 加密端口,net462 等旧框架自动启用 TLS 1.2)

ExportHelper

CSV 导出:ExportCVS(fileName, rows, csvSeparator = ',', coding = null),rows 为 List<List<string>>。

  • 默认编码为 UTF-8(带 BOM),各目标框架一致,Excel 可直接识别中文。

    ⚠️ 2.7.0 起的行为变更:此前默认 Encoding.Default,在 .NET Framework 下实际是 GBK。下游若按 GBK 读取导出文件,请显式传入 Encoding.GetEncoding("GB2312")。

  • 按 RFC 4180 转义:字段含分隔符、双引号、回车或换行时整体加引号,内部双引号加倍。

SystemInfo

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

  • GetAppSetting(key) / GetConfigValue(key) — 读取配置项
  • GetConnString(name) / GetConnStruct(name) — 读取数据库连接串
  • ReloadConfig() — 重新加载配置
  • ToBoolean(value, default) — 支持 true/false 与 1/0
  • ProcessStartTime — 实际进程启动时间(受限环境下退化为本类首次加载时间)
  • 另含 GUID、日期格式化、路径、类型判断等杂项工具。

DB(数据库映射辅助)

配合 DBColAttribute + 反射实现实体与数据行/存储过程参数的映射:

  • DBUtil.Convert / DeConvert — 实体与数据源对象互转
  • DBHelper — 存储过程入/出参装配、DB 值与类型解析;输入与输入输出参数(Direction 1/3)都会从实体取值,输出参数可回填到可空类型与枚举属性
  • DBParse — 安全取值(GetSafeInt / GetSafeDate / GetSafeDecimal / GetSafeStr 等),null 与 DBNull 均返回安全默认值
  • NConvert — 数值/日期/布尔转换,含金额转大写 ToCapital(有“分”时不再追加“整”)
  • SqlUtil.GetWhere(paramDict, tableAlias) — 由字典拼接 WHERE 条件。空列表生成恒假条件 1=0(不再被丢弃成不过滤);数值按不变区域性输出,bool 转 1/0,枚举转底层数值,Guid/char 加引号转义;其他类型抛 ArgumentException(请改用参数化查询)

⚠️ XYS.Utils.DB 包中定义了同名的 XYS.Utils.DB.DBHelper、NConvert 等类型,同时引用两个包会出现 CS0433 类型冲突。请只引用 XYS.Utils.Sys。


配置加密:Crypto(2.6.0)

保护 xys.config.json 中的敏感值(如数据库连接串),避免明文密码泄露。

  • 算法:AES-256-CBC + HMAC-SHA256(Encrypt-then-MAC),全 5 个目标框架原生,无第三方依赖。
  • 密钥优先级:Crypto.SetKey(...) > 环境变量 XYS_CRYPTO_KEY > 内置默认密钥。

加密连接串并写回配置

用测试工程内的便捷工具生成密文(PowerShell):

$env:XYS_ENC_INPUT = 'Server=db;User Id=app;Password=真实密码;'
# 若使用自有密钥,同时设置:$env:XYS_CRYPTO_KEY = '你的密钥'
dotnet test XYS.Utils.Sys.Tests --filter FullyQualifiedName~ConnStrEncryptTool

把输出的 ENC(...) 整行贴回配置:

{
  "connectionStrings": {
    "his": {
      "connectionString": "ENC(base64....)",
      "providerName": "Microsoft.Data.SqlClient"
    }
  }
}

SystemInfo.GetConnStruct("his") 会自动解密;不带 ENC(...) 的明文原样返回,现有配置无需改动即可继续运行。DataFactory / 其他经 GetConnStruct 的消费方无需改代码即受益。

密钥与安全说明

  • 内置默认密钥为混淆级:持有程序集者可反出并解密。它挡的是"看到配置即泄露"(误提交 git、运维翻配置、备份/截图),不是已取得服务器全部文件的攻击者。
  • 强防护:在应用启动时 Crypto.SetKey("站点专属密钥"),或设置环境变量 XYS_CRYPTO_KEY(密钥不入程序集、不入源码)。宿主亦可将 DPAPI/KMS 作为密钥源接入 SetKey。
  • 更换密钥后,旧密钥加密的 ENC(...) 需用新密钥重新生成。

版本

当前版本 2.7.0。

2.7.0 变更

升级前请留意标注 ⚠️ 的行为变更。

  • ⚠️ HttpJsonUtil.AllowUntrustedCertificate 默认改为 false(默认校验 HTTPS 证书);net462 下不再改写进程级证书回调。
  • ⚠️ SqlUtil.GetWhere:空列表生成 1=0;不支持的值类型抛 ArgumentException;修复全为空列表时生成 where where 1=1。
  • ⚠️ ExportHelper.ExportCVS 默认编码改为 UTF-8(带 BOM)。
  • ConvertUtil.TryParse(long) 修复大数精度丢失。
  • Crypto.Unprotect 缓存解密结果,加密连接串不再每次读取都耗时约 80ms。
  • NConvert.ToCapital、DBHelper 输出参数类型转换、DBParse 的 DBNull 处理、XmlUtil.TypeConvert 异常处理等问题修复。
  • HttpJsonUtil 超时可超过 100 秒、空响应按错误返回、req 为 null 时不再抛空引用。
  • MailHelper 支持 ENC(...) 密码且不再修改传入的请求对象。
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 (20)

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

Package Downloads
XYS.FR

Package Description

XYS.DataFactory

Package Description

XYS.Utils.DB

Package Description

XYS.Utils.Web

Package Description

XYS.Mongo

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.7.0 177 11/16/2026
2.6.0 385 7/25/2026
2.5.0 360 7/22/2026
2.3.3 227 7/21/2026
2.3.2 196 7/16/2026
2.3.1 235 7/14/2026
2.2.1.4 299 1/7/2026
2.2.1.2 919 12/7/2023
2.2.1.1 640 12/4/2023
2.1.2.1 602 11/24/2023
2.1.1.2 299 10/27/2023
2.1.1.1 593 5/15/2023
2.1.0.10 466 2/13/2023
2.1.0.9 602 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
2.1.0.4 6,157 6/7/2022
Loading failed