Healnet.Common
2.0.0
See the version list below for details.
dotnet add package Healnet.Common --version 2.0.0
NuGet\Install-Package Healnet.Common -Version 2.0.0
<PackageReference Include="Healnet.Common" Version="2.0.0" />
<PackageVersion Include="Healnet.Common" Version="2.0.0" />
<PackageReference Include="Healnet.Common" />
paket add Healnet.Common --version 2.0.0
#r "nuget: Healnet.Common, 2.0.0"
#:package Healnet.Common@2.0.0
#addin nuget:?package=Healnet.Common&version=2.0.0
#tool nuget:?package=Healnet.Common&version=2.0.0
Healnet.Common 通用模块
版本: v1.5.0 | TFM: net10.0 | 独立引用 | NuGet: Healnet.Common 1.5.0
概述
Healnet.Common 是 Healnet 微服务框架的基础通用工具类库,提供跨项目共享的加密工具、JSON 序列化、ID 生成器、扩展方法、DTO 基类和 Excel 处理等功能。作为整个框架的底层依赖,为 Core 和 Infrastructure 层提供基础支撑。
核心特性
- ✅ 加密工具 - AES/RSA/Hash 加密解密辅助方法 (
CryptoHelper) - ✅ JSON 序列化 - 高性能 JSON 序列化/反序列化 (
JsonHelper) - ✅ 雪花 ID - 分布式唯一 ID 生成器 (
IdGenerator) - ✅ 扩展方法 - String/Object/DateTime/Collection 扩展方法
- ✅ DTO 基类 - AuditableDto/BaseDto/PaginationDto 通用数据传输对象
- ✅ Excel 处理 - 基于 ClosedXML 的 Excel 导入导出 (
ExcelService) - ✅ Mapster 映射 - Mapster 扩展配置 (
MapsterExtensions) - ✅ FluentValidation - 验证器扩展方法 (
FluentValidationExtensions) - ✅ 业务枚举 - 通用业务枚举定义 (
BusinessEnums) - ✅ 应用常量 - 系统级常量定义 (
AppConstants) - ✅ 集成事件 - 分布式事件基础类型 (
IntegrationEvent)
核心组件
1. 工具类 (Helpers)
| 类 | 命名空间 | 说明 |
|---|---|---|
CryptoHelper |
Healnet.Common.Helpers |
加密工具:AES、RSA、MD5、SHA256、HMAC |
DateHelper |
Healnet.Common.Helpers |
日期时间工具:Unix 时间戳转换、日期计算 |
EnvironmentHelper |
Healnet.Common.Helpers |
环境变量检测:开发/生产/测试环境识别 |
IdGenerator |
Healnet.Common.Helpers |
雪花算法分布式 ID 生成器 |
JsonHelper |
Healnet.Common.Helpers |
JSON 序列化/反序列化:System.Text.Json 封装 |
NetworkHelper |
Healnet.Common.Helpers |
网络工具:IP 地址获取、端口检测 |
RandomHelper |
Healnet.Common.Helpers |
随机数/随机字符串生成 |
ServiceAddressHelper |
Healnet.Common.Helpers |
服务地址解析与构建 |
StringHelper |
Healnet.Common.Helpers |
字符串处理工具 ⚠️ [已标记为 Obsolete] |
ValidationHelper |
Healnet.Common.Helpers |
数据验证:邮箱、手机号、身份证等格式校验 |
2. 扩展方法 (Extensions)
| 类 | 扩展类型 | 说明 |
|---|---|---|
StringExtensions |
string |
字符串判空、HTML 编码、Base64 编解码、URL 编码 |
ObjectExtensions |
object |
类型转换、深拷贝、属性克隆 |
DateTimeExtensions |
DateTime |
日期范围计算、工作日判断、时间差格式化 |
CollectionExtensions |
IEnumerable<T> |
集合分组、批量插入、去重、分页 |
3. 数据传输对象 (Models)
| 类 | 命名空间 | 说明 |
|---|---|---|
BaseDto |
Healnet.Common.Models |
DTO 基类:创建时间、修改时间审计字段 |
AuditableDto |
Healnet.Common.Models |
可审计 DTO:增加创建人、修改人字段 |
PaginationDto |
Healnet.Common.Models |
分页参数:页码、每页数量、排序字段 |
4. 文件存储 (FileStorage)
| 类 | 命名空间 | 说明 |
|---|---|---|
FileService |
Healnet.Common.FileStorage |
文件服务抽象基类 |
ExcelService |
Healnet.Common.FileStorage.Excel |
Excel 导入导出服务:基于 ClosedXML |
5. 其他模块
| 模块 | 命名空间 | 说明 |
|---|---|---|
| 映射扩展 | Healnet.Common.Mapping |
Mapster ITypeAdapterConfigurator 扩展 |
| 验证扩展 | Healnet.Common.Validation |
FluentValidation AbstractValidator 扩展 |
| 业务枚举 | Healnet.Common.Enums |
通用业务枚举:状态、类型、分类等 |
| 应用常量 | Healnet.Common.Constants |
系统常量:缓存前缀、消息队列路由键等 |
| 集成事件 | Healnet.Common.Events |
分布式集成事件基类:IntegrationEvent |
依赖关系
graph LR
A[Healnet.Common] --> B[FluentValidation]
A --> C[Mapster]
A --> D[ClosedXML]
A --> E[Microsoft.AspNetCore.Http.Abstractions]
使用指南
1. 加密工具
using Healnet.Common.Helpers;
// AES 加密/解密
string plaintext = "Hello World";
string key = CryptoHelper.GenerateAesKey();
string encrypted = CryptoHelper.AesEncrypt(plaintext, key);
string decrypted = CryptoHelper.AesDecrypt(encrypted, key);
// SHA256 哈希
string hash = CryptoHelper.Sha256Hash("password123");
// MD5 哈希
string md5 = CryptoHelper.Md5Hash("password123");
2. JSON 序列化
using Healnet.Common.Helpers;
var obj = new { Name = "Healnet", Version = "1.5.0" };
// 序列化为 JSON 字符串
string json = JsonHelper.Serialize(obj);
// 反序列化
var result = JsonHelper.Deserialize<MyModel>(json);
// 安全序列化(处理循环引用)
string safeJson = JsonHelper.SerializeSafe(obj);
3. 雪花 ID 生成
using Healnet.Common.Helpers;
// 默认实例
long id = IdGenerator.GenerateId();
// 自定义实例(设置数据中心和工作区 ID)
var customGenerator = new IdGenerator(datacenterId: 1, workerId: 1);
long customId = customGenerator.GenerateId();
4. 扩展方法
using Healnet.Common.Extensions;
// 字符串扩展
string name = " Hello World ";
string trimmed = name.TrimEx(); // 智能修剪
bool isEmpty = name.IsEmpty(); // 判空(含空白字符)
string base64 = name.ToBase64(); // Base64 编码
string decoded = base64.FromBase64(); // Base64 解码
// 集合扩展
var list = new List<int> { 1, 2, 3, 4, 5, 6 };
var paged = list.ToPagedList(1, 2); // 分页
var grouped = list.GroupByBatch(2); // 分批
5. DTO 基类
using Healnet.Common.Models;
// 基础 DTO
public class UserDto : BaseDto
{
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
// 可审计 DTO
public class OrderDto : AuditableDto
{
public string OrderNo { get; set; } = string.Empty;
public decimal TotalAmount { get; set; }
}
// 分页查询参数
public class QueryParams : PaginationDto
{
public string? Keyword { get; set; }
public DateTime? StartDate { get; set; }
}
6. Excel 处理
using Healnet.Common.FileStorage.Excel;
// 导出数据到 Excel
var data = new List<UserDto> { /* ... */ };
await excelService.ExportAsync(data, "users.xlsx");
// 从 Excel 导入数据
var imported = await excelService.ImportAsync<UserDto>("users.xlsx");
NuGet 包信息
| 属性 | 值 |
|---|---|
| PackageId | Healnet.Common |
| 当前版本 | 1.5.0 |
| 目标框架 | net10.0 |
| 许可证 | LICENSE |
| 仓库 | github.com/healnet/healnet-framework |
版本历史
| 版本 | 日期 | 变更说明 |
|------|------|----------|
| v1.5.0 | 2026-06-16 | 新增 EnvironmentHelper、NetworkHelper、RandomHelper、ServiceAddressHelper;重构 IdGenerator;移除 Newtonsoft.Json 依赖;标记 StringHelper 为 Obsolete |
| v1.4.0 | - | 版本统一升级 |
}
### 2. 工具类使用
```csharp
// 字符串工具
string trimmed = StringHelper.TrimToNull(" hello "); // "hello"
string hash = StringHelper.GenerateHash("password"); // 哈希值
bool isEmail = StringHelper.IsEmail("test@example.com"); // true
string mask = StringHelper.MaskEmail("test@example.com"); // "t***@example.com"
// 日期时间工具
DateTime now = DateTimeHelper.Now; // 当前 UTC 时间
string formatted = DateTimeHelper.Format(DateTime.Now, "yyyy-MM-dd HH:mm:ss");
DateTime parsed = DateTimeHelper.Parse("2024-01-01");
int days = DateTimeHelper.GetDaysBetween(startDate, endDate);
bool isWorkDay = DateTimeHelper.IsWorkDay(DateTime.Now);
// 集合工具
List<int> list = CollectionHelper.EmptyIfNull(nullList);
bool hasItems = CollectionHelper.HasItems(list);
List<int> distinct = CollectionHelper.RemoveDuplicates(list);
Dictionary<string, int> dict = CollectionHelper.ToDictionary(list, item => item.ToString());
// 加密工具
string encrypted = EncryptionHelper.Encrypt("secret", "key");
string decrypted = EncryptionHelper.Decrypt(encrypted, "key");
string md5 = EncryptionHelper.Md5Hash("text");
string sha256 = EncryptionHelper.Sha256Hash("text");
string token = EncryptionHelper.GenerateToken();
// 验证工具
bool isValid = ValidationHelper.IsValidEmail("test@example.com");
bool isMobile = ValidationHelper.IsValidMobile("13800138000");
bool isIdCard = ValidationHelper.IsValidIdCard("110101199003077758");
bool isUrl = ValidationHelper.IsValidUrl("https://example.com");
3. 扩展方法使用
// 字符串扩展
string str = "Hello World";
bool isNullOrEmpty = str.IsNullOrEmpty(); // false
bool isNotNullOrEmpty = str.IsNotNullOrEmpty(); // true
string trimmed = str.SafeTrim(); // "Hello World"
string lower = str.ToLowerInvariant(); // "hello world"
string upper = str.ToUpperInvariant(); // "HELLO WORLD"
bool contains = str.ContainsIgnoreCase("world"); // true
string substring = str.SafeSubstring(0, 5); // "Hello"
string[] split = str.SplitTrim(','); // ["Hello World"]
// 日期时间扩展
DateTime date = DateTime.Now;
string formatted = date.ToStandardFormat(); // "2024-01-15 10:30:00"
string dateOnly = date.ToDateString(); // "2024-01-15"
string timeOnly = date.ToTimeString(); // "10:30:00"
bool isToday = date.IsToday(); // true
bool isYesterday = date.IsYesterday(); // false
DateTime startOfDay = date.StartOfDay(); // 00:00:00
DateTime endOfDay = date.EndOfDay(); // 23:59:59
DateTime nextWeek = date.AddWeeks(1); // 一周后
// 集合扩展
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
bool isNullOrEmpty = numbers.IsNullOrEmpty(); // false
bool hasItems = numbers.HasItems(); // true
int? first = numbers.FirstOrNull(); // 1
int? last = numbers.LastOrNull(); // 5
List<int> even = numbers.WhereNotNull(); // 过滤空值
List<string> strList = numbers.Select(x => x.ToString()).ToList();
// 对象扩展
object obj = null;
bool isNull = obj.IsNull(); // true
bool isNotNull = obj.IsNotNull(); // false
string json = obj.ToJson(); // "null"
T clone = obj.Clone(); // 深拷贝
// 枚举扩展
OrderStatus status = OrderStatus.Pending;
string name = status.GetName(); // "Pending"
string description = status.GetDescription(); // "待处理"
int value = status.GetValue(); // 1
bool hasFlag = status.HasFlag(OrderStatus.Pending); // true
4. 分页结果
public class UserService
{
public PagedResult<User> GetPagedUsers(int page, int pageSize)
{
var query = _userRepository.GetAllQueryable();
var totalCount = query.Count();
var items = query.Skip((page - 1) * pageSize).Take(pageSize).ToList();
return new PagedResult<User>
{
Items = items,
Page = page,
PageSize = pageSize,
TotalCount = totalCount,
TotalPages = (int)Math.Ceiling((double)totalCount / pageSize)
};
}
}
// 使用
var result = userService.GetPagedUsers(1, 10);
foreach (var user in result.Items)
{
Console.WriteLine(user.Name);
}
Console.WriteLine($"共 {result.TotalCount} 条,共 {result.TotalPages} 页");
5. 通用结果类型
public Result<string> ValidateInput(string input)
{
if (string.IsNullOrEmpty(input))
{
return Result<string>.Failure("输入不能为空");
}
if (input.Length < 6)
{
return Result<string>.Failure("输入长度不能小于6");
}
return Result<string>.Success(input);
}
// 使用
var result = ValidateInput("test");
if (result.IsSuccess)
{
Console.WriteLine($"有效输入: {result.Data}");
}
else
{
Console.WriteLine($"错误: {result.Message}");
}
6. 配置帮助类
// 从配置获取字符串
string connectionString = ConfigurationHelper.GetString("ConnectionStrings:Default");
// 从配置获取整数
int timeout = ConfigurationHelper.GetInt("AppSettings:Timeout", 30);
// 从配置获取布尔值
bool enabled = ConfigurationHelper.GetBool("AppSettings:Enabled", true);
// 从配置获取对象
var settings = ConfigurationHelper.GetSection<AppSettings>("AppSettings");
// 强类型配置
public class AppSettings
{
public string ApiUrl { get; set; } = string.Empty;
public int Timeout { get; set; } = 30;
public bool EnableLogging { get; set; } = true;
}
// 使用 IOptions
public class MyService
{
private readonly AppSettings _settings;
public MyService(IOptions<AppSettings> settings)
{
_settings = settings.Value;
}
public void DoSomething()
{
Console.WriteLine($"API URL: {_settings.ApiUrl}");
}
}
7. 反射工具
// 获取类型属性
var properties = ReflectionHelper.GetProperties<User>();
// 获取属性值
object value = ReflectionHelper.GetPropertyValue(user, "Name");
// 设置属性值
ReflectionHelper.SetPropertyValue(user, "Name", "New Name");
// 检查类型是否实现接口
bool implements = ReflectionHelper.ImplementsInterface<User, IEntity>();
// 创建实例
User user = ReflectionHelper.CreateInstance<User>();
// 获取方法
MethodInfo method = ReflectionHelper.GetMethod<User>("GetById");
// 调用方法
object result = ReflectionHelper.InvokeMethod(user, "ToString");
常量定义示例
public static class ClaimTypes
{
public const string UserId = "sub";
public const string Email = "email";
public const string Role = "role";
public const string Name = "name";
public const string TenantId = "tenantId";
public const string Permissions = "permissions";
}
public static class CacheKeys
{
public const string UserPrefix = "User:";
public const string TokenPrefix = "Token:";
public const string ConfigPrefix = "Config:";
public static string User(long userId) => $"{UserPrefix}{userId}";
public static string RefreshToken(string token) => $"{TokenPrefix}{token}";
}
public static class PolicyNames
{
public const string AdminOnly = "AdminOnly";
public const string ManagerOrAdmin = "ManagerOrAdmin";
public const string TenantAccess = "TenantAccess";
}
public static class HttpHeaders
{
public const string Authorization = "Authorization";
public const string ContentType = "Content-Type";
public const string XRequestId = "X-Request-Id";
public const string XTenantId = "X-Tenant-Id";
}
依赖包
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.0" />
项目结构
┌─────────────────────────────────────────────────────────────┐
│ Healnet.Common │
├─────────────────────────────────────────────────────────────┤
│ Helpers │
│ ├── StringHelper.cs │
│ ├── DateTimeHelper.cs │
│ ├── CollectionHelper.cs │
│ ├── EncryptionHelper.cs │
│ ├── ValidationHelper.cs │
│ ├── ReflectionHelper.cs │
│ └── ConfigurationHelper.cs │
├─────────────────────────────────────────────────────────────┤
│ Extensions │
│ ├── StringExtensions.cs │
│ ├── DateTimeExtensions.cs │
│ ├── CollectionExtensions.cs │
│ ├── ObjectExtensions.cs │
│ └── EnumExtensions.cs │
├─────────────────────────────────────────────────────────────┤
│ Models │
│ ├── ApiResponse.cs │
│ ├── PagedResult.cs │
│ ├── Result.cs │
│ └── AuditInfo.cs │
├─────────────────────────────────────────────────────────────┤
│ Constants │
│ ├── ClaimTypes.cs │
│ ├── CacheKeys.cs │
│ ├── PolicyNames.cs │
│ └── HttpHeaders.cs │
└─────────────────────────────────────────────────────────────┘
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. 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. |
-
net10.0
- ClosedXML (>= 0.102.0 && < 0.103.0)
- FluentValidation (>= 11.0.0 && < 12.0.0)
- FluentValidation.DependencyInjectionExtensions (>= 11.0.0 && < 12.0.0)
- Mapster (>= 7.4.0 && < 8.0.0)
- Microsoft.AspNetCore.Http.Abstractions (>= 2.2.0 && < 3.0.0)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on Healnet.Common:
| Package | Downloads |
|---|---|
|
Healnet.Infrastructure
Healnet.Infrastructure 是 Healnet 框架的基础设施层类库,提供各种基础设施服务的封装和集成,包括 Consul 服务发现、Redis 缓存、RabbitMQ 消息队列、gRPC、Elasticsearch、Milvus 向量数据库、SQLSugar ORM、JWT 认证、YARP 反向代理、OpenTelemetry 可观测性、Serilog 日志框架、ClickHouse 列式数据库等。 |
|
|
Healnet.Core
Healnet.Core 是 Healnet 框架的核心业务层类库,提供领域层的基础接口和通用服务。包含仓储接口、工作单元、消息队列接口和统一异常处理。 |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 3.0.0 | 59 | 7/16/2026 |
| 2.0.7 | 109 | 7/10/2026 |
| 2.0.5 | 113 | 7/8/2026 |
| 2.0.3 | 117 | 6/30/2026 |
| 2.0.1 | 102 | 6/30/2026 |
| 2.0.0 | 116 | 6/29/2026 |
| 1.7.3 | 113 | 6/29/2026 |
| 1.5.0 | 143 | 6/16/2026 |
| 1.4.0 | 116 | 6/15/2026 |
| 1.2.0 | 120 | 5/29/2026 |
| 1.1.1 | 118 | 5/25/2026 |
| 1.1.0 | 120 | 5/22/2026 |
| 1.0.9 | 123 | 5/20/2026 |
| 1.0.8 | 118 | 5/20/2026 |
| 1.0.7 | 113 | 5/20/2026 |
| 1.0.6 | 142 | 5/19/2026 |
| 1.0.5 | 162 | 5/13/2026 |
| 1.0.4 | 125 | 5/13/2026 |
| 1.0.3 | 122 | 5/13/2026 |
| 1.0.2 | 118 | 5/13/2026 |
v1.5.0: 新增 EnvironmentHelper/NetworkHelper/RandomHelper/ServiceAddressHelper;重构 IdGenerator;移除 Newtonsoft.Json 依赖;标记 StringHelper 为 Obsolete