XiheNet 1.2.0

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

XiheNet

XiheNet 是一个 .NET 工具类库,提供常用静态函数、数据实体和工具方法。

安装

通过 NuGet 安装:

dotnet add package XiheNet

快速开始

using XiheNet;

// 统一响应
var response = XResponse.Success(new { Id = 1, Name = "Test" });
var error = XResponse.Error("1001", "操作失败");

// 文件资源实体
var resource = new XResourceEntity
{
    url = "/upload/2405/file.jpg",
    name = "file.jpg",
    size = "1024"
};

API 文档

响应实体 (XResponse)

提供统一的 API 响应格式,包含响应头 (RespHead) 和响应体 (RespBody)。

静态工厂方法
方法 说明
XResponse.Success<T>(T body, string code = "0000", string message = "OK") 创建成功响应
XResponse.Error(string code, string message) 创建错误响应
使用示例
// 成功响应
return XResponse.Success(new User { Id = 1, Name = "张三" });

// 错误响应
return XResponse.Error("1001", "用户不存在");

// 使用空响应体
return XResponse.Success(new EmptyBody());
响应结构
{
  "RespHead": { "Code": "0000", "Message": "OK" },
  "RespBody": { "Id": 1, "Name": "张三" }
}

资源实体 (XResourceEntity)

统一的文件资源实体,用于描述图片、文档、视频等文件资源。

属性
属性 类型 说明
url string 文件访问地址
name string 文件原始名称
size string 文件大小(图片类型可为空)
使用示例
// 图片资源(size 可空)
var cover = new XResourceEntity
{
    url = "/cover/2405/2405-guid.jpg",
    name = "cover.jpg"
};

// 文件资源
var file = new XResourceEntity
{
    url = "/novel/2405/2405-guid.txt",
    name = "章节.txt",
    size = "1024"
};

// 数据库存储(JSON 序列化)
List<XResourceEntity> fileList = new() { file };
string json = JsonConvert.SerializeObject(fileList);

注意: 旧版本 XPicEntity 和 XFileEntity 已标记为过时,请迁移至 XResourceEntity。


工具类 (XUtils)

生成随机字符串 (GetRandomStr)
string randomStr = XUtils.GetRandomStr(16, isSpecialChar: false, isNum: true);
参数 类型 默认值 说明
length int - 生成字符串的长度
isSpecialChar bool false 是否包含特殊字符 (!@#$%^&*)
isNum bool true 是否包含数字
isLowLetter bool true 是否包含小写字母
isUpLetter bool true 是否包含大写字母
获取当前请求 URL (GetUri)
// 获取当前站点域名
string domain = XUtils.GetUri(request, true, false);

// 获取当前页面完整链接
string fullUrl = XUtils.GetUri(request, true, true, true, true);

// 获取页面相对路径
string relativePath = XUtils.GetUri(request, false, false, true, true);
参数 类型 默认值 说明
Request HttpRequest - 当前请求
IsAbsolute bool true 是否为绝对地址
ContainScheme bool true 是否包含网络协议(仅绝对地址有效)
ContainPath bool false 是否包含相对路径
ContainQuery bool false 是否包含请求参数(仅包含路径时有效)
获取希禾规则文件路径 (GetXiheFilePath)
string filePath = XUtils.GetXiheFilePath("2409-guid.jpg", "cover", "https://example.com");
// 返回: https://example.com/cover/2409/2409-guid.jpg
构建文件完整 URL (BuildFileUrl)

统一构建文件 URL,支持两种模式:

// 模式1:通用路径拼接
string url1 = XUtils.BuildFileUrl("/path/file.jpg", "https://example.com");
// 返回: https://example.com/path/file.jpg

// 模式2:希禾规则(传入 prefix 时自动使用希禾规则)
string url2 = XUtils.BuildFileUrl("2409-guid.jpg", "https://example.com", "cover");
// 返回: https://example.com/cover/2409/2409-guid.jpg

// 支持 URL 后缀(如 OSS 参数)
string url3 = XUtils.BuildFileUrl("/path/file.jpg", "https://example.com", "", "?x-oss-process=resize");
// 返回: https://example.com/path/file.jpg?x-oss-process=resize
其他方法
方法 说明
GetAgeByBirthday(DateTime birthday) 根据出生日期计算年龄
Md5Encryp(string txt, int bit = 32, string charset = "UTF-8") MD5 加密
SHA1Encryp(string txt) SHA1 加密
EncryptWithSalt(string password, string salt) 使用盐值加密密码
MaskString(string input, int startLen, int endLen, char maskChar = '*') 字符串掩码处理
NormalizeFilePath(string filePath, string domain) 标准化文件路径(移除域名)
使用盐值加密 (EncryptWithSalt)
string encrypted = XUtils.EncryptWithSalt("password123", "random_salt");
字符串掩码 (MaskString)
// 手机号掩码:138****8888
string masked = XUtils.MaskString("13812345678", 3, 4);

// 邮箱掩码:t***@example.com
string emailMasked = XUtils.MaskString("test@example.com", 1, 11);
文件路径处理
// 标准化文件路径(移除域名)
string relative = XUtils.NormalizeFilePath("https://example.com/path/file.jpg", "example.com");
// 返回: /path/file.jpg

常用字典 (XDict)

// 是否
XDict.Whether.Yes   // 1
XDict.Whether.No    // 0

// 性别
XDict.Sex.Male      // 1
XDict.Sex.Female    // -1

// 支付方式
XDict.PayType.Balance   // 0
XDict.PayType.Alipay    // 1
XDict.PayType.WeChat    // 2

// 支付状态
XDict.PayStatus.Unpaid  // 0
XDict.PayStatus.Success // 1
XDict.PayStatus.Failed  // -1

// 审核状态
XDict.ExamineStatus.Unsubmitted // 0
XDict.ExamineStatus.Pending     // 1
XDict.ExamineStatus.Approved    // 2
XDict.ExamineStatus.Rejected    // -1

// 认证状态
XDict.CertStatus.Uncertified    // 0
XDict.CertStatus.Certifying     // 1
XDict.CertStatus.Success        // 2
XDict.CertStatus.Failed         // -1

// OSS 图片压缩参数
XDict.OssPicture.Headimg  // ?x-oss-process=image/resize,m_fill,h_100,w_100
XDict.OssPicture.Cover    // ?x-oss-process=image/resize,l_300
XDict.OssPicture.Picture  // ?x-oss-process=image/resize,l_600

时间戳库 (XTimestamp)

// 获取当前时间戳
long timestamp = XTimestamp.dt2ts(DateTime.Now);

// 时间戳转时间
DateTime dt = XTimestamp.ts2dt(timestamp);

// 时间戳格式化
string formatted = XTimestamp.Format(timestamp, "time");     // yyyy-MM-dd HH:mm:ss
string date = XTimestamp.Format(timestamp, "date");         // yyyy-MM-dd
string cnDate = XTimestamp.Format(timestamp, "cnDate");     // yyyy年MM月dd日

数值函数库 (XNumber)

int num = XNumber.ToInt("123", 0);       // 转整数
double dbl = XNumber.ToDbl("123.45", 0); // 转双精度浮点数
decimal dec = XNumber.ToDec("123.45", 0);// 转高精度浮点数
long lng = XNumber.ToLng("123", 0);      // 转长整数

接口请求 (XRequest)

// POST 异步请求
string result = await XRequest.PostAsync("https://api.example.com", jsonContent);

// POST 同步请求
string result = XRequest.Post("https://api.example.com", jsonContent);

// GET 请求
string result = XRequest.Get("https://api.example.com");

格式校验 (XCheck)

// 创建待校验数据
Dictionary<string, string> FormData = new Dictionary<string, string>
{
    { "UserName", "testuser" },
    { "Mobile", "13800138000" }
};

// 创建校验规则
List<RuleConfig> Rules = new List<RuleConfig>()
{
    new RuleConfig
    {
        Field = "UserName",
        Rules = new List<dynamic>
        {
            new { Rule = "Required", Message = "用户名必填" },
            new { Rule = "Length", Message = "用户名长度6-12位", Min = 6, Max = 12 }
        }
    },
    new RuleConfig
    {
        Field = "Mobile",
        Rules = new List<dynamic>
        {
            new { Rule = "Required", Message = "手机号码必填" },
            new { Rule = "Regex", Message = "手机号码格式不正确", Presets = "RegMobile" }
        }
    }
};

// 执行校验
XCheck check = new();
CheckResult result = check.Check(FormData, Rules);
校验规则
规则 说明 参数
Required 必填校验 -
Length 长度校验 Min, Max
Regex 正则校验 Presets (预设名) 或 Regex (自定义正则)
Number 数值范围校验 Min, Max
Function 函数校验 Presets (预设函数名)
预设正则表达式
预设名 说明
RegUrl 网址
RegMobile 手机号
RegTelephone 固定电话
RegEmail 邮箱
RegIp IP 地址
RegDate 日期 (yyyy-MM-dd)
RegDatetime 日期时间 (yyyy-MM-dd HH:mm:ss)
RegAmount 金额
RegPassword 密码 (6-18位,无空格)
RegCarCode 车牌号
RegIntP 正整数
RegFloat2P 最多2位小数的正实数
预设函数校验
预设名 说明
BankcardCheck 银行卡有效性校验
IDCardCheck 身份证有效性校验

迁移指南

XPicEntity / XFileEntity → XResourceEntity

// 旧代码 (已过时)
var pic = new XPicEntity { url = "/path/img.jpg", name = "img.jpg" };
var file = new XFileEntity { url = "/path/file.txt", name = "file.txt", size = "1024" };

// 新代码
var resource = new XResourceEntity
{
    url = "/path/file.txt",
    name = "file.txt",
    size = "1024"  // 图片可为空
};

更新日志

v1.2.0

新增

  • XResourceEntity: 统一的文件资源实体,整合图片和文件资源描述
  • XResponse 静态工厂方法: Success<T>() 和 Error(),简化响应创建
  • XUtils.EncryptWithSalt: 使用盐值加密密码
  • XUtils.MaskString: 字符串掩码处理(手机号、邮箱等脱敏)
  • XUtils.NormalizeFilePath: 标准化文件路径(移除域名部分)
  • XUtils.BuildFileUrl: 构建文件完整 URL(整合 GetXiheFilePath 功能,支持两种模式)

变更

  • XPicEntity 标记为 [Obsolete],建议迁移至 XResourceEntity
  • XFileEntity 标记为 [Obsolete],建议迁移至 XResourceEntity

迁移指南

旧类型 新类型 说明
XPicEntity XResourceEntity size 字段可为空
XFileEntity XResourceEntity 字段完全兼容

许可证

MIT License

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  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 was computed.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on XiheNet:

Package Downloads
XiheNet.Data

Package Description

XiheNet.Ali

Package Description

XiheNet.Wechat

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.2.0 162 3/17/2026
1.1.3 392 12/15/2024
1.1.1 345 2/14/2024
1.0.1 459 9/13/2023