Healnet.Common
1.1.1
There is a newer version of this package available.
See the version list below for details.
See the version list below for details.
dotnet add package Healnet.Common --version 1.1.1
NuGet\Install-Package Healnet.Common -Version 1.1.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="Healnet.Common" Version="1.1.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Healnet.Common" Version="1.1.1" />
<PackageReference Include="Healnet.Common" />
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 Healnet.Common --version 1.1.1
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: Healnet.Common, 1.1.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 Healnet.Common@1.1.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=Healnet.Common&version=1.1.1
#tool nuget:?package=Healnet.Common&version=1.1.1
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
Healnet.Common 通用模块
概述
Healnet.Common 是 Healnet 框架的通用工具模块,提供跨项目共享的工具类、扩展方法、常量定义和基础类型,是整个框架的基础设施支撑。
核心特性
- ✅ 通用工具类 - 字符串、日期、集合等工具方法
- ✅ 扩展方法 - 增强现有类型的功能
- ✅ 常量定义 - 项目通用常量
- ✅ 基础类型 - 通用 DTO、枚举、异常类型
- ✅ 配置帮助类 - 简化配置读取
- ✅ 加密工具 - 加密解密辅助方法
- ✅ 验证工具 - 数据验证辅助方法
- ✅ 反射工具 - 反射操作辅助方法
核心组件
1. 工具类
| 类 | 说明 |
|---|---|
StringHelper |
字符串处理工具 |
DateTimeHelper |
日期时间处理工具 |
CollectionHelper |
集合操作工具 |
EncryptionHelper |
加密解密工具 |
ValidationHelper |
数据验证工具 |
ReflectionHelper |
反射操作工具 |
ConfigurationHelper |
配置读取工具 |
2. 扩展方法
| 类别 | 说明 |
|---|---|
StringExtensions |
字符串扩展方法 |
DateTimeExtensions |
日期时间扩展方法 |
CollectionExtensions |
集合扩展方法 |
ObjectExtensions |
对象扩展方法 |
EnumExtensions |
枚举扩展方法 |
3. 基础类型
| 类型 | 说明 |
|---|---|
ApiResponse<T> |
统一 API 响应格式 |
PagedResult<T> |
分页结果 |
Result<T> |
通用结果类型 |
ErrorResult |
错误结果 |
AuditInfo |
审计信息 |
KeyValuePair<TKey, TValue> |
键值对 |
4. 常量
| 常量类 | 说明 |
|---|---|
ClaimTypes |
JWT 声明类型常量 |
CacheKeys |
缓存键常量 |
PolicyNames |
授权策略名称 |
HttpHeaders |
HTTP 头常量 |
EnvironmentNames |
环境名称 |
使用指南
1. 统一 API 响应
// 成功响应
public IActionResult GetUser(long id)
{
var user = _userService.GetById(id);
return Ok(ApiResponse<User>.SuccessResult(user));
}
// 成功响应(无数据)
public IActionResult DeleteUser(long id)
{
_userService.Delete(id);
return Ok(ApiResponse.Success("删除成功"));
}
// 错误响应
public IActionResult CreateUser([FromBody] UserDto dto)
{
try
{
var user = _userService.Create(dto);
return Created(ApiResponse<User>.SuccessResult(user));
}
catch (Exception ex)
{
return BadRequest(ApiResponse.Error(400, ex.Message));
}
}
// 分页响应
public IActionResult GetUsers(int page, int pageSize)
{
var pagedResult = _userService.GetPaged(page, pageSize);
return Ok(ApiResponse<PagedResult<User>>.SuccessResult(pagedResult));
}
2. 工具类使用
// 字符串工具
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. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net10.0
- ClosedXML (>= 0.102.1)
- FluentValidation (>= 11.4.0)
- FluentValidation.DependencyInjectionExtensions (>= 11.4.0)
- Mapster (>= 7.4.0)
- Microsoft.AspNetCore.Http.Abstractions (>= 2.2.0)
- Newtonsoft.Json (>= 13.0.3)
- System.Security.Cryptography.Xml (>= 8.0.1)
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.1.0 | 41 | 7/24/2026 |
| 3.0.1 | 71 | 7/23/2026 |
| 3.0.0 | 94 | 7/16/2026 |
| 2.0.7 | 112 | 7/10/2026 |
| 2.0.5 | 114 | 7/8/2026 |
| 2.0.3 | 118 | 6/30/2026 |
| 2.0.1 | 104 | 6/30/2026 |
| 2.0.0 | 116 | 6/29/2026 |
| 1.7.3 | 114 | 6/29/2026 |
| 1.5.0 | 145 | 6/16/2026 |
| 1.4.0 | 116 | 6/15/2026 |
| 1.2.0 | 121 | 5/29/2026 |
| 1.1.1 | 119 | 5/25/2026 |
| 1.1.0 | 120 | 5/22/2026 |
| 1.0.9 | 125 | 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 |
Loading failed
Initial release of Healnet.Common