Rabbit.Common.Lite 1.3.1

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

Rabbit.Common.Lite

Core utility package providing logging, encryption, JSON, configuration, string/collection extensions, pagination, validation, file I/O, compression, and reflection helpers. Required by all other Rabbit.Common packages.

.NET 基础工具包,提供日志、加密、JSON、类型转换、扩展方法等常用功能。

安装

dotnet add package Rabbit.Common.Lite

依赖

  • Serilog 4.3.1
  • Microsoft.Extensions.DependencyInjection 10.0.4
  • Microsoft.AspNetCore.Cryptography.KeyDerivation 10.0.4

配置管理 (ConfigHelper)

支持 Web 和 Console 项目的配置读取。

Web API 项目

var builder = WebApplication.CreateBuilder(args);
ConfigHelper.Initialize(builder.Configuration);

Console 项目

using Microsoft.Extensions.Configuration;
using Rabbit.Common;

// 方式一:从 JSON 文件加载(推荐)
ConfigHelper.InitializeFromJson("appsettings.json");

// 方式二:从 JSON 文件加载(配置文件可选)
ConfigHelper.InitializeFromJson("appsettings.json", optional: true);

// 方式三:手动构建配置
var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .Build();
ConfigHelper.Initialize(config);

// 检查是否已初始化
if (ConfigHelper.IsInitialized)
{
    var value = ConfigHelper.GetValue("Key");
}

// 使用
var connectionString = ConfigHelper.GetValue("ConnectionStrings:Default");
var maxRetry = ConfigHelper.GetValue("AppSettings:MaxRetry", "3");

功能模块

日志 (Serilog)

using Rabbit.Common;
using Rabbit.Common.Extensions;

// 注册服务(支持自定义目录)
services.AddSeriLogMapConfigure(
    logPath: "logs",
    logFileName: "api",
    defaultSecondPath: "default",
    fileSizeLimitMb: 100,
    retainedFileCountLimit: 15
);

// 使用
LogHelper.LogInformation("操作成功");
LogHelper.LogError(exception, "发生错误");
LogHelper.LogWarning("警告信息");
LogHelper.LogDebug("调试信息");

// 自定义二级目录
LogHelper.LogInformation("订单日志", customPath: "order");
LogHelper.LogError(exception, "支付错误", customPath: "payment");

JSON 序列化

using Rabbit.Common;

// 序列化
var json = JsonHelper.Serialize(user);
var json = JsonHelper.Serialize(user,
    timeFormat: "yyyy-MM-dd HH:mm:ss",
    naming: NamingPolicyEnum.CamelCase,
    ignoreNull: true);

// 反序列化
var user = JsonHelper.Deserialize<User>(json);

// 深度克隆
var clone = JsonHelper.Clone(user);

// 扩展方法
var json = user.JsonSerialize();
var obj = json.JsonDeserialize<User>();
var clone = user.JsonClone();

加密解密

using Rabbit.Common;

// AES 加密/解密
var encrypted = EncryptionHelper.AesEncrypt("明文", "密钥");
var decrypted = EncryptionHelper.AesDecrypt(encrypted, "密钥");

// RSA 加密/解密
var (publicKey, privateKey) = EncryptionHelper.GenerateRsaKeyPair();
var encrypted = EncryptionHelper.RsaEncrypt("明文", publicKey);
var decrypted = EncryptionHelper.RsaDecrypt(encrypted, privateKey);

// 哈希
var sha256 = EncryptionHelper.Sha256Hash("内容");
var md5 = EncryptionHelper.Md5Hash("内容");
var hmac = EncryptionHelper.HmacSha256("内容", "密钥");

// 密码哈希(推荐用于用户密码存储)
var hash = EncryptionHelper.CreatePasswordHash("密码");
var valid = EncryptionHelper.VerifyPasswordHash("密码", hash);

类型转换

using Rabbit.Common;

// 安全转换
int num = ConvertHelper.TryToInt32("123", defaultValue: 0);
long bigNum = ConvertHelper.TryToInt64("123456789", defaultValue: 0);
double d = ConvertHelper.TryToDouble("3.14", defaultValue: 0.0);
decimal dec = ConvertHelper.TryToDecimal("99.99", defaultValue: 0m);
string str = ConvertHelper.TryToString(obj, defaultValue: "");

// 格式化小数
double rounded = ConvertHelper.ToRound(3.14159, digits: 2);  // 3.14

枚举扩展

using Rabbit.Common;

// 枚举转 int
int code = ApiStatusCodeEnum.Success_0.ToInt();

// int 转枚举
var status = 200.ToEnum<ApiStatusCodeEnum>();
var status = 200.ToEnumOrDefault<ApiStatusCodeEnum>();

// 获取 Description
string desc = ApiStatusCodeEnum.Success_200.GetDescription();
string desc = 200.GetEnumDescription<ApiStatusCodeEnum>();

// 获取所有枚举值和描述
var all = EnumExtension.GetAllValuesAndDescriptions<ApiStatusCodeEnum>();

字符串扩展

using Rabbit.Common.Extensions;

// 判断
if (str.IsNullOrEmpty()) { }
if (str.HasValue()) { }
if (str.IsNullOrWhiteSpace()) { }

// 转换
var camelCase = "HelloWorld".ToCamelCase();  // helloWorld
var pascalCase = "helloWorld".ToPascalCase();  // HelloWorld
var snakeCase = "HelloWorld".ToSnakeCase();  // hello_world
var kebabCase = "HelloWorld".ToKebabCase();  // hello-world

// 截取
var left = "Hello World".Left(5);  // Hello
var right = "Hello World".Right(5);  // World
var truncated = "Hello World".Truncate(8);  // Hello...

// 掩码
var phone = "13812345678".MaskPhone();  // 138****5678
var email = "test@example.com".MaskEmail();  // t***@example.com

// 比较
if (str.EqualsIgnoreCase("HELLO")) { }
if (str.ContainsIgnoreCase("hello")) { }

日期时间转换

using Rabbit.Common.Helper;

// 时间戳转换
var timestamp = DateTimeConvertHelper.ToUnixTimestampSeconds(DateTime.Now);
var dt = DateTimeConvertHelper.ToDateTimeFromUnixTimestamp(timestamp);

// 字符串转 DateTime
var dt = "2024-01-01".TryToDateTime();

// DateTime 转字符串
var str = DateTime.Now.DateTimeTryToString("yyyy-MM-dd HH:mm:ss");

集合操作

using Rabbit.Common;

// 空值检查
if (list.IsNullOrEmpty()) { }
if (list.HasValue()) { }

// 安全获取
var safe = list.OrEmpty();
var safe = list.OrDefault(defaultList);

// 分页
var page = list.Page(pageIndex: 1, pageSize: 10);

// 批处理
foreach (var batch in list.Batch(100))
{
    ProcessBatch(batch);
}

// 树形结构
var tree = items.ToTree(
    idSelector: x => x.Id,
    parentIdSelector: x => x.ParentId,
    rootId: null
);

// 随机
var random = list.RandomElement();
var shuffled = list.Shuffle();

分页

using Rabbit.Common.Helper;

// 生成分页结果
var paged = PaginationHelper.CreatePagedResult(items, totalCount, page, pageSize);

// 分页信息
var info = PaginationHelper.CreatePaginationInfo(page, pageSize, totalCount);
Console.WriteLine($"总页数: {info.TotalPages}");
Console.WriteLine($"起始索引: {info.StartIndex}");

API 响应

using Rabbit.Common;

// 成功响应
return ApiResponseHelper.Success(data);
return data.ToApiResponse();

// 错误响应
return ApiResponseHelper.Fail("操作失败");

// 分页响应
return list.ToPagedApi(totalCount, pageIndex, pageSize);

DI 接口标记

using Rabbit.Common.Dto;

// 使用接口标记自动注入
public interface IUserService : IScopedInterface { }

public class UserService : IUserService { }
// 自动注册为 Scoped 生命周期

// 支持的标记接口
// - ITransientInterface → Transient
// - IScopedInterface → Scoped
// - ISingletonInterface → Singleton

自动注册服务

using Rabbit.Common.Extensions;

// 扫描程序集自动注册
services.AddAssemblyServices(typeof(Program).Assembly);

扩展方法列表

方法 说明
AddSeriLogMapConfigure 注册 Serilog(支持自定义目录)
AddJsonConfigure 配置 JSON 序列化选项
AddConfigurationConfigure 注册配置文件
ToInt 枚举转 int
ToEnum<T> int 转枚举
GetDescription 获取枚举 Description
IsNullOrEmpty 判断字符串/集合是否为空
HasValue 判断字符串/集合是否有值
ToCamelCase 转换为驼峰命名
ToPascalCase 转换为帕斯卡命名
ToSnakeCase 转换为下划线命名
JsonSerialize 对象序列化为 JSON
JsonDeserialize JSON 反序列化为对象
JsonClone 深度克隆对象
ToPagedApi 列表转分页响应
ToApiResponse 数据转 API 响应

许可证

MIT

Product 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.

NuGet packages (10)

Showing the top 5 NuGet packages that depend on Rabbit.Common.Lite:

Package Downloads
Rabbit.Common.Full

Meta-package referencing all Rabbit.Common utility packages. / Rabbit.Common 全家桶,引用所有子包

Rabbit.Common.RateLimit

Rate limiting with token bucket and sliding window algorithms, memory or Redis storage. / 限流组件,支持令牌桶和滑动窗口算法,可用于分布式限流

Rabbit.Common.Redis

Two-level caching (Memory + Redis via FreeRedis) with multi-instance support. / Redis 缓存组件,支持二级缓存(内存 + Redis)和多实例管理

Rabbit.Common.Data.Dapper

Dapper micro-ORM component supporting MySQL and SQL Server with transactions and batch operations. / Dapper 数据库访问组件,支持 SQL Server 和 MySQL

Rabbit.Common.Auth

JWT authentication for ASP.NET Core with HttpContext user claim extensions. / JWT 认证组件,提供用户声明获取和认证配置

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.3.1 194 5/28/2026
1.3.0 198 5/19/2026
1.2.1 191 4/7/2026
1.2.0 182 3/27/2026
1.1.0 199 3/12/2026
1.0.0 193 3/12/2026