XYS.Utils.Web 3.0.1

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

XYS.Utils.Web

Web 相关工具类库,提供基于 RestSharp 的高并发同步/异步 REST 调用封装(HttpRestUtil),以及带空闲超时控制的文件下载客户端(NovaWebClient)。

目标框架

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

依赖


HttpRestUtil

基于 RestSharp 的静态 REST 工具类,命名空间 XYS.Utils.Web。按归一化后的 baseUrl 复用 RestClient(线程安全缓存、禁用共享 Cookie、5 分钟连接生命周期自动刷新 DNS),适用于高并发场景;T 支持任意可由 Newtonsoft.Json 反序列化的类型(实体、数组、集合、record 或字符串,无需无参构造函数)。

基本用法

using XYS.Utils.Web;

// 异步:对象体(内部自动紧凑序列化为 JSON)
var result = await HttpRestUtil.PostAsync<ResultDto>(
    "https://api.example.com", "/order/create", new { id = 1, name = "test" });

// 异步:直接传已序列化好的 JSON 字符串(原样发送,避免二次序列化)
var result2 = await HttpRestUtil.PostAsync<ResultDto>(
    "https://api.example.com", "/order/create", "{\"id\":1}");

// 异步/同步:无请求体 POST(body 传 null 或省略)
var cancelRes = await HttpRestUtil.PostAsync<ResultDto>(
    "https://api.example.com", "/order/1001/cancel");

// 同步(内部已做请求级超时隔离与线程池监控)
var result3 = HttpRestUtil.PostSync<ResultDto>(
    "https://api.example.com", "/order/create", new { id = 1 });

// GET:查询参数支持匿名对象/实体(识别 [JsonProperty] 与 [JsonIgnore])
var result4 = await HttpRestUtil.GetAsync<ResultDto[]>(
    "https://api.example.com", "/order/list", new { id = 1, name = "test" });

// GET:查询参数也支持 Dictionary / IReadOnlyDictionary / ExpandoObject
var result5 = HttpRestUtil.GetSync<ResultDto>(
    "https://api.example.com", "/order/detail",
    new Dictionary<string, object> { ["id"] = 1 });

// 表单提交(multipart/form-data):服务端以表单字段接收,字段值本身可为 JSON 字符串
var result7 = HttpRestUtil.PostFormSync<ResultDto>(
    "https://api.example.com", "/gateway",
    new Dictionary<string, string>
    {
        ["interfaceName"] = "doctor",
        ["methodName"]    = "getPatientEmrContentById",
        ["data"]          = "{\"recordId\":\"xxx\",\"contentType\":\"html\"}",
    });
  • 超时隔离:所有方法均支持 timeoutMs 参数(默认 30000ms,传 ≤0 时按默认 30000ms 处理),异步方法额外支持 CancellationToken。
  • 查询参数格式化:值为 null 或标注 [JsonIgnore] 的属性自动跳过;标注 [JsonProperty("...")] 时使用指定参数名;参数值与系统区域设置无关地格式化(日期为 ISO 8601 2026-11-19T08:30:00,数值用 . 作小数点,布尔为小写 true/false,byte[] 为 Base64),集合值按同名键重复展开(ids=1&ids=2)。

异常与返回语义

情形 行为
2xx 且响应为有效 JSON 返回反序列化后的 T(空响应体或 204 返回 default(T))
baseUrl 为空或非 HTTP/HTTPS 绝对地址 抛 ArgumentException
调用方通过 CancellationToken 取消 抛 OperationCanceledException
超过 timeoutMs 抛 TimeoutException
非 2xx、网络错误、200 非法 JSON 反序列化失败 抛 Exception(InnerException 为底层异常)

失败时日志与异常消息中的响应内容最多保留 1024 个字符,超出部分截断,避免敏感数据与大段错误页整段写入日志。

序列化

内部统一使用 Newtonsoft.Json(通过 RestSharp.Serializers.NewtonsoftJson 配置),与 XYS.Utils.Sys.HttpJsonUtil 保持一致:请求/响应实体及查询参数对象上的 [JsonProperty] / [JsonIgnore] 特性均生效。

认证 Token 与自定义请求头

支持全局默认头、Bearer Token 提供者与单次请求头三层叠加,同名头按 单次请求 headers > AuthTokenProvider > DefaultHeaderProvider 覆盖:

// 1. 全局默认头(启动时注入一次)
HttpRestUtil.DefaultHeaderProvider = () => new Dictionary<string, string>
{
    ["X-Api-Key"] = "your-api-key",
    ["X-Tenant"]  = "hospital-001",
};

// 2. 全局认证 Token(返回 null/空时不附加 Authorization 头)
HttpRestUtil.AuthTokenProvider = () => UserSession.Current?.Token;

// 3. 单次请求头(可覆盖全局默认头或默认 Authorization)
var result = await HttpRestUtil.PostAsync<ResultDto>(
    "https://api.example.com", "/order/create", new { id = 1 },
    headers: new Dictionary<string, string> { ["X-Request-Id"] = Guid.NewGuid().ToString() });

TLS 协议与证书校验

  • 在 net462 等旧框架下自动启用 TLS 1.2(不影响系统默认协商 TLS 1.3)。
  • 默认开启标准 TLS 证书校验;内网自签名/过期证书部署可在启动时显式放行:
HttpRestUtil.AllowUntrustedCertificate = true;

高并发与连接池说明

  • RestClient 按归一化后的 baseUrl 缓存,同一地址仅创建一次实例,复用底层连接池。
  • 底层 HttpMessageHandler 禁用共享 CookieContainer(避免服务端 Set-Cookie 跨用户串号),并配置 5 分钟连接生命周期(PooledConnectionLifetime / ServicePoint.ConnectionLeaseTimeout)兼顾连接复用与 DNS 刷新。
  • 同步方法监控线程池可用工作线程数并在过低或回调严重滞后时输出诊断告警。

NovaWebClient

继承自 WebClient 的文件下载客户端,命名空间 XYS.Utils.Web,支持底层读写超时与“无进度即超时取消”的空闲检测。

using XYS.Utils.Web;

using var client = new NovaWebClient { Timeout = 5000 }; // 毫秒(≤0 回退默认 3000ms)
client.DownloadFileAsyncWithTimeout(new Uri("https://.../big.zip"), "big.zip", null);
  • Timeout 单位为毫秒(默认 3000ms),毫秒级精度作用于底层请求及空闲超时计时。
  • 下载过程中每收到一次数据即无锁重置计时;在超时时间内无任何数据到达则自动取消下载。
  • 下载结束(成功、失败或取消)先停止计时再触发外部 DownloadFileCompleted 事件,支持在回调内安全复用同一实例发起链式下载;Dispose() 自动释放内部计时器资源。
  • CalculateTime 基于单调时钟与线程池 Timer 实现,同时提供 Timeout(秒)与 TimeoutMilliseconds(毫秒)属性。

版本

当前版本 3.0.1。

  • 3.0.1:
    • HttpRestUtil:补齐 net462 TLS 1.2 自动启用;底层 Handler 禁用共享 Cookie 并启用 5 分钟连接生命周期(刷新 DNS);校验并归一化 baseUrl;移除公开方法的 where T : new() 约束并支持无请求体 POST(body = null);GET 查询参数支持 ExpandoObject、IReadOnlyDictionary、byte[] 及 [JsonProperty]/[JsonIgnore](带类型反射缓存);固定请求头覆盖优先级(单次 headers > AuthTokenProvider > DefaultHeaderProvider);修正同步线程池饥饿超时诊断与日志透传。
    • NovaWebClient / CalculateTime:消除回调链式下载误停新计时器与极快完成竞态;修复 .NET Core / .NET 8 下流挂起时 CancelAsync() 无法中断响应流的缺陷;重写 Dispose 释放计时器并取消未完成下载;CalculateTime 改用单调时钟 + 线程池 Timer 并新增毫秒级 TimeoutMilliseconds 属性。
    • 随包输出各目标框架 XML 文档注释,移除未使用的项目依赖。
  • 3.0.0(不兼容变更):
    • AllowUntrustedCertificate 默认值由 true 改为 false:使用自签名证书的内网部署须在启动时显式设为 true。
    • 取消改为抛 OperationCanceledException,超时改为抛 TimeoutException(两者均派生自 Exception)。
    • 查询参数改为与区域设置无关的格式,布尔值由 True 变为 true。
    • 删除遗留的 XYS.Utils.Web.Net462.csproj(net462 由 SDK 项目多目标覆盖)。
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 (2)

Showing the top 2 NuGet packages that depend on XYS.Utils.Web:

Package Downloads
XYS.Lab.Report

Description

XYS.CDR.Lab

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.0.1 84 11/30/2026
3.0.0 94 11/28/2026
2.5.0 177 7/22/2026
2.4.0 144 7/21/2026
2.3.2 143 7/21/2026
2.3.1 138 7/21/2026
2.1.0.4 208 1/8/2026
2.1.0.3 179 1/7/2026
2.1.0.2 706 5/7/2022
2.1.0.1 1,956 1/23/2022
2.0.2.2 887 12/21/2021
2.0.2.1 565 12/20/2021
2.0.1.2 553 12/20/2021
2.0.1.1 6,076 4/22/2021
1.0.1.1 761 5/25/2020
1.0.0.10 1,229 5/27/2020