SilanCore 1.0.23

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

SilanCore 组件使用说明

目录

  1. 组件概述
  2. 快速开始
  3. 核心服务
  4. 统一基类体系
  5. 工具类库
  6. 扩展方法库
  7. 特性与常量定义
  8. 接口抽象层
  9. 配置参考
  10. 扩展规划

一、组件概述

1.1 定位

SilanCore 是基于 ASP.NET Core 8.0 封装的业务基础组件库,提供企业级应用开发所需的通用基础设施能力。

1.2 核心能力

能力模块 说明
统一基类 控制器/服务/DTO/日志四层基类体系
接口包装 统一响应格式封装(ApiResponseDto)
异常处理 全局异常捕获 + 自动告警 + 递归异常信息
日志记录 自动请求日志、链路追踪、调用者信息记录
邮件服务 支持内外网邮件发送
短信服务 阿里云短信发送
定时任务 Hangfire 原生规范集成
Excel 操作 基于 NPOI 的读写、多 Sheet、样式支持
HTTP 请求 基于 RestSharp 的统一 HTTP 客户端
加密解密 SHA/MD5/AES/RSA/Base64 全覆盖
ID 生成 GUID + 雪花算法分布式唯一 ID
重试机制 基于 Polly 的指数退避重试
数据库访问 多数据库连接 + Dapper 集成 + 事务管理
文件操作 文件读写/复制/移动/下载/类型识别
Razor 渲染 视图模板渲染为 HTML 字符串
网络共享 SMB/UNC 共享路径访问
HTML 生成 List/Json 转 HTML 表格
扩展方法 字符串/日期/集合/反射等链式扩展

1.3 设计原则

  • 配置化:所有第三方服务均通过 appsettings.json 配置
  • 构造注入:依赖注入风格统一,易于测试与维护
  • 开箱即用:最小化接入成本
  • 规范适配:严格遵循第三方库最新官方规范(无过时 API)

二、快速开始

2.1 接入三步曲

Step 1:添加配置

// appsettings.json 中添加所需服务的配置项
// 详见第五章【配置参考】

Step 2:注册服务

// Program.cs 中注册所需服务
builder.Services.AddScoped<EmailService>(...);
builder.Services.AddScoped<SmsService>(...);
builder.Services.AddScoped<HangfireService>(...);

Step 3:控制器继承

public class YourController : BaseController
{
    public YourController(EmailService emailService, EmailMessageDto emailMessageDto) 
        : base(emailService, emailMessageDto)
    { }
}

三、核心服务

3.1 邮件服务(EmailService)

3.1.1 功能特性
  • 自动识别内网/外网邮件发送
  • 支持单条、批量、异步发送
  • 支持 HTML 模板与附件
  • 全局异常自动触发告警邮件
3.1.2 配置项
// 内网邮件服务器(必填)
"InternalEmailServer": {
  "emailServer": "smtp.server.local",
  "port": 25,
  "username": "notice@company.com",
  "password": "YourPasswordHere",
  "useSsl": true
},

// 外网邮件服务器(可选,用于外网场景)
"ExternalOutEmailServer": {
  "emailServer": "smtp.company.com",
  "port": 25,
  "username": "",
  "password": "",
  "useSsl": false
},

// 外网收件服务器(可选)
"ExternalInEmailServer": {
  "emailServer": "imap.company.com",
  "port": 993,
  "username": "",
  "password": "",
  "useSsl": true
},

// 异常告警邮件配置(可选,推荐启用)
"ApiErrorEmailMessage": {
  "senderName": "系统告警",
  "senderEmail": "notice@company.com",
  "username": "notice@company.com",
  "password": "YourPasswordHere",
  "emailType": 0,
  "toRecipientList": [ "admin@company.com" ],
  "subject": "系统接口执行异常告警"
}
3.1.3 服务注册
// 注册邮件服务
var internalEmailConfig = builder.Configuration.GetSection("InternalEmailServer").Get<EmailServerDto>();
builder.Services.AddScoped<EmailService>(sp => new EmailService(internalEmailConfig));

// 注册告警邮件配置(如需自动告警)
var apiErrorEmailConfig = builder.Configuration.GetSection("ApiErrorEmailMessage").Get<EmailMessageDto>();
builder.Services.AddScoped(apiErrorEmailConfig);
3.1.4 使用示例
public class TestController : BaseController
{
    private readonly EmailService _emailService;
    
    public TestController(EmailService emailService, EmailMessageDto emailMessageDto) 
        : base(emailService, emailMessageDto)
    {
        _emailService = emailService;
    }

    public async Task SendEmail()
    {
        // 构造邮件内容
        var emailDto = new EmailMessageDto
        {
            toRecipientList = new List<string> { "user@company.com" },
            subject = "测试邮件",
            body = "<h1>Hello World</h1>",
            isBodyHtml = true
        };
        
        // 发送邮件
        await _emailService.SendAsync(emailDto);
    }
}

3.2 短信服务(SmsService)

3.2.1 功能特性
  • 单条/批量短信发送
  • 验证码模板专用方法
  • 阿里云 AK 配置化管理
3.2.2 配置项
"AlibabaCloudSms": {
  "accessKeyId": "your-access-key-id",
  "accessKeySecret": "your-access-key-secret",
  "endpoint": "dysmsapi.aliyuncs.com",
  "SignName": "短信签名",
  "VerificationCodeTemplateCode": "验证码模板CODE"
}
3.2.3 服务注册
// 注册阿里云认证服务
var smsAuthConfig = builder.Configuration.GetSection("AlibabaCloudSms").Get<SmsAuthDto>();
builder.Services.AddScoped<SmsAuthService>(sp => new SmsAuthService(smsAuthConfig));

// 注册短信服务
var smsOptions = builder.Configuration.GetSection("AlibabaCloudSms").Get<SmsOptions>();
builder.Services.AddScoped<SmsService>(sp => 
    new SmsService(sp.GetRequiredService<SmsAuthService>(), smsOptions));
3.2.4 使用示例
public class SmsController : BaseController
{
    private readonly SmsService _smsService;
    
    public SmsController(SmsService smsService, EmailService emailService, EmailMessageDto emailMessageDto) 
        : base(emailService, emailMessageDto)
    {
        _smsService = smsService;
    }

    public IActionResult SendCode()
    {
        var smsDto = new SmsMessageDto<SmsVerificationCodeTemplateParamDto>
        {
            phoneNumbers = "13800138000",
            templateParam = new SmsVerificationCodeTemplateParamDto 
            { 
                code = "123456" 
            }
        };
        
        _smsService.SendVerificationCode(smsDto);
        return Success();
    }
}

3.3 定时任务服务(HangfireService)

3.3.1 功能特性
  • 严格遵循 Hangfire 最新官方规范,无过时 API 警告
  • 拆分服务注册与中间件配置,符合 ASP.NET Core 架构
  • 支持自定义仪表盘授权
  • SQL Server 存储 + Schema 隔离
  • 与 SilanCore 日志体系统一
3.3.2 配置项
"Hangfire": {
  "ConnectionString": "DatabaseConnectionString",
  "DashboardUrl": "/hangfire",
  "SchemaName": "Hangfire"
}
3.3.3 服务注册(Program.cs)
// 读取 Hangfire 配置
var hangfireConfig = builder.Configuration.GetSection("Hangfire").Get<HangfireConfigDto>() 
    ?? throw new InvalidOperationException("Hangfire 配置不存在");

// 注册 Hangfire 业务服务
builder.Services.AddScoped<HangfireService>(sp => new HangfireService(hangfireConfig));

// 注册 Hangfire 存储 & 后台服务(官方最新规范)
var hangfireServiceForRegistration = new HangfireService(hangfireConfig);
hangfireServiceForRegistration.RegisterStorage(builder.Services);
3.3.4 启用仪表盘与注册任务
var app = builder.Build();

// 从容器获取服务
var hangfireService = app.Services.GetRequiredService<HangfireService>();

// 启用仪表盘并注册业务定时任务
hangfireService.UseDashboardAndRegisterJobs(app, RegisterJobs);

// 定时任务注册示例
void RegisterJobs()
{
    RecurringJob.AddOrUpdate(
        "TestJob",
        () => Console.WriteLine("Hangfire 定时任务执行"),
        Cron.Minutely);
}

app.Run();

四、统一基类体系

SilanCore 提供四层基类体系,覆盖控制器、服务、数据传输与日志,业务代码继承即可获得标准化能力。

4.1 控制器基类 BaseController

所有业务控制器继承 BaseController 后自动获得以下能力:

能力 说明
统一响应包装 标准化 API 返回格式(ApiResponseDto)
自动日志记录 记录请求入参、出参、耗时
全局异常捕获 自动处理未捕获异常
异常告警 生产环境自动发送告警邮件(需配置)
同步/异步支持 提供 HandleResponse / HandleResponseAsync 两套方法
使用示例
public class UserController : BaseController
{
    public UserController(EmailService emailService, EmailMessageDto emailMessageDto) 
        : base(emailService, emailMessageDto) { }

    public async Task<IActionResult> GetUser(int userId)
    {
        return await HandleResponseAsync(async () => 
        {
            return await _userService.GetUserAsync(userId);
        }, "查询成功", "查询用户失败");
    }
}

4.2 服务基类 BaseService

BaseService 继承自 BaseLog,实现 IService 接口,为业务服务层提供统一的操作执行框架。

能力 说明
统一操作执行 同步/异步操作包装,自动日志与异常处理
内置常量 分页、排序、状态、编码等业务通用常量
环境感知 自动读取当前运行环境标识
日志集成 继承 BaseLog,自动获取 Logger 实例
使用示例
public class UserService : BaseService
{
    public IActionResult GetUser(int userId)
    {
        return HandleResponse(() => 
        {
            return new { id = userId, name = "张三" };
        }, "查询成功", "查询失败");
    }
}

4.3 数据传输基类 BaseDto

BaseDto<TKey> 提供实体类通用字段,支持泛型主键类型,内置审计字段与软删除标记。

字段 类型 说明
id TKey 主键 ID(支持 int/long/string)
createdTime DateTime 创建时间
createdBy string 创建人 ID
updatedTime DateTime? 更新时间
updatedBy string 更新人 ID
isDeleted string 软删除标记
预置派生类
类名 主键类型 适用场景
BaseIntDto int 自增整型主键
BaseLongDto long 雪花算法长整型主键
BaseStringDto string 字符串主键(如 UUID)
使用示例
public class UserDto : BaseIntDto
{
    public string name { get; set; }
    public string email { get; set; }
}

4.4 日志基类 BaseLog

BaseLog 实现 ILog 接口,为所有需要日志能力的类提供统一的 Logger 实例。

能力 说明
自动 Logger 根据实现类完整类型名自动创建 Logger
统一接口 实现 ILog 接口,便于依赖注入与测试
public class MyBusinessService : BaseLog
{
    public void DoWork()
    {
        _logger.Info("开始执行业务逻辑");
        // 业务代码...
    }
}

五、工具类库

SilanCore 提供丰富的静态工具类,覆盖企业开发常见场景,开箱即用。

5.1 Excel 工具 ExcelUtils

基于 NPOI 封装的通用 Excel 操作类,支持读写、多 Sheet、样式设置。

功能特性
  • 强类型读取:Excel 文件/流 → List<T>
  • 灵活写入:单 Sheet / 多 Sheet 写入
  • 样式可扩展:通过 IExcelStyleProvider 自定义样式
  • 数据转换可扩展:通过 IExcelDataConverter 自定义类型转换
使用示例
// 读取 Excel 为强类型列表
List<UserDto> users = ExcelUtils.Read<UserDto>("data.xlsx", sheetIndex: 0);

// 从流读取
List<UserDto> users = ExcelUtils.ReadFromStream<UserDto>(fileStream);

// 写入单 Sheet Excel
ExcelUtils.Write(users, "output.xlsx", sheetName: "用户列表", title: "用户数据报表");

// 写入多 Sheet Excel
Dictionary<string, (IEnumerable DataList, string Title)> sheetData = new()
{
    { "用户列表", (users, "用户数据") },
    { "订单列表", (orders, "订单数据") }
};
ExcelUtils.WriteMultipleSheets(sheetData, "report.xlsx");

5.2 HTTP 请求工具 HttpUtils

基于 RestSharp 封装的 HTTP 客户端工具,提供统一的请求发送能力。

功能特性
  • 支持所有 HTTP 方法(GET/POST/PUT/DELETE 等)
  • 通过 HttpRequestDto 统一配置请求参数
  • 文件流响应智能识别(图片/文档/压缩包等)
使用示例
// 判断响应是否为文件流
bool isFile = HttpUtils.IsStreamResponse(response);

5.3 加密工具 EncryptUtils

提供常见的哈希加密算法和对称/非对称加解密算法。

功能特性
算法类型 支持算法
哈希算法 SHA-1 / SHA-256 / SHA-384 / SHA-512 / MD5
对称加密 AES(ECB 模式,PKCS7 填充)
非对称加密 RSA(2048 位,PKCS#1 填充)
编码转换 Base64 编解码
使用示例
// 哈希加密
string sha256 = EncryptUtils.Sha256("Hello World");
string md5 = EncryptUtils.Md5("Hello World", isUppercase: true);

// AES 对称加解密
string encrypted = EncryptUtils.AesEncrypt("敏感数据");
string decrypted = EncryptUtils.AesDecrypt(encrypted);

// RSA 非对称加解密
var keys = EncryptUtils.GenerateRsaKeys();
string cipher = EncryptUtils.RsaEncrypt("数据", keys["PublicKey"].ToString());
string plain = EncryptUtils.RsaDecrypt(cipher, keys["PrivateKey"].ToString());

// Base64
string encoded = EncryptUtils.Base64Encode("Hello");
string decoded = EncryptUtils.Base64Decode(encoded);

安全提示:AES-ECB 模式存在安全风险,建议生产环境使用 CBC/GCM 模式;SHA-1 已存在碰撞风险,高安全场景推荐 SHA-256 及以上。

5.4 ID 生成工具 IdUtils

提供 UUID 与雪花算法两种 ID 生成方案。

方法 说明
GenerateGuid() 生成 32 位小写 GUID(无连字符)
GenerateGuidUpper() 生成 32 位大写 GUID
GenerateSnowflakeId() 生成分布式唯一 long 型 ID(Yitter 雪花算法)
使用示例
string guid = IdUtils.GenerateGuid();           // 如:a3f5e2b1c4d8...
long snowflakeId = IdUtils.GenerateSnowflakeId(); // 如:1234567890123456789

5.5 重试工具 PollyUtils

基于 Polly 封装的通用重试工具,支持指数退避策略。

功能特性
  • 同步/异步重试执行
  • 可配置最大重试次数与初始退避秒数
  • 指数退避:backoff = baseSeconds × 2^(attempt-1)
  • 自动记录每次重试日志
使用示例
// 同步重试(默认 3 次,初始退避 1 秒)
var result = PollyUtils.Execute(() => 
{
    return CallExternalApi();
}, maxRetryCount: 5, backoffSeconds: 2);

// 异步重试
var data = await PollyUtils.ExecuteAsync(async () => 
{
    return await httpClient.GetAsync(url);
}, maxRetryCount: 3);

5.6 数据库工具 DatabaseUtils

提供多数据库连接创建能力,配合 Dapper 实现 ORM 操作。

功能特性
  • 支持 SQL Server / MySQL(Oracle / PostgreSQL 预留)
  • 通过 DatabaseConnectionConfigDto 统一配置
  • 自动生成连接字符串
  • 连接生命周期管理
使用示例
var config = new DatabaseConnectionConfigDto(
    server: "localhost",
    port: 1433,
    databaseName: "MyDB",
    databaseType: DatabaseTypeEnum.SqlServer,
    userId: "sa",
    password: "password",
    timeout: 30
);

using IDbConnection connection = DatabaseUtils.CreateConnection(config);
var users = connection.Query<UserDto>("SELECT * FROM Users").ToList();
事务管理扩展
using var transaction = connection.BeginTransaction();
try
{
    // 业务操作...
    transaction.Commit(useTransaction: true);
}
catch
{
    transaction.Rollback(useTransaction: true);
    throw;
}
finally
{
    transaction.Dispose();
}

5.7 文件工具 FileUtils

提供文件和目录的创建、读取、写入、删除、复制、移动等操作。

功能特性
能力 方法
存在性检查 IsDirectoryOrFileExist / EnsureDirectoryOrFileExist
目录遍历 GetSubFolder / GetSubFile / GetSubFolderAndFile
文件读取 GetFileTextContent / GetFileByte / GetReadStream
文件写入 GetWriteStream / WriteStream2file
文件下载 DownloadFile / DownloadFileAsync(支持网络路径与字节数据)
文件操作 CopyFileToDirectory / RenameFile / Move / DeleteFileSafely
类型识别 GetFileExtension / GetFileType / FileExtension2FileType
使用示例
// 确保文件存在
FileUtils.EnsureDirectoryOrFileExist("logs/app.log");

// 读取文件内容
string content = FileUtils.GetFileTextContent("config.json");

// 下载网络文件
var fileDto = new FileDto 
{ 
    name = "report.pdf", 
    networkPath = "https://example.com/report.pdf",
    downloadType = FileDownloadTypeConstants.NetworkPath
};
await fileDto.DownloadFileAsync();

// 获取文件类型
FileTypeEnum fileType = FileUtils.GetFileType("document.xlsx");

5.8 Razor 渲染工具 RazorUtils

将 Razor 视图模板渲染为 HTML 字符串,常用于邮件模板生成。

使用示例
public class NotificationController : BaseController
{
    public IActionResult SendNotification()
    {
        var model = new { userName = "张三", content = "您的订单已发货" };
        string html = this.RenderView("~/Views/Shared/EmailTemplates/Notification.cshtml", model);
        
        // 发送 HTML 邮件
        var emailDto = new EmailMessageDto { body = html, isBodyHtml = true };
        _emailService.SendEmail(emailDto);
        return Success();
    }
}

5.9 其他工具类

工具类 说明
ConfigurationUtils 全局配置读取(需启动时 Initialize)
LoggerUtils 调用者信息日志记录(堆栈追踪)
DateTimeUtils 时间戳/日期计算/日期差值
NetworkUtils SMB/UNC 共享路径访问与操作
SqlScriptsUtils SQL 脚本文件读取(UTF-8/GB2312)
ExceptionUtils 递归获取多层内部异常信息
HtmlUtils List/Json 转 HTML 表格
StyleUtils HTML 表格 CSS 样式生成
JsonUtils JSON 序列化配置管理
PlaywrightUtils 浏览器自动化(Chromium)
ConfigurationUtils 使用
// Program.cs 启动时初始化
ConfigurationUtils.Initialize(builder.Configuration);

// 任意位置读取配置
string env = ConfigurationUtils.GetConfiguration("Environment");
string connStr = ConfigurationUtils.GetConfiguration("ConnectionStrings:Default");
DateTimeUtils 使用
long timestamp = DateTimeUtils.GetMillisecondsTimestamp();
DateTime now = DateTimeUtils.GetCurrentDateTime();
int days = DateTimeUtils.GetDayDifference(startDate, endDate, getAbsoluteValue: true);
NetworkUtils 使用
// 检查共享路径可访问
bool accessible = NetworkUtils.CheckUncPathConnect(@"\\192.168.1.100\share", "user", "pass");

// 在共享连接中执行操作
NetworkUtils.ExecuteWithUncConnection(client => 
{
    // SMB 文件操作...
    return true;
}, @"\\192.168.1.100\share", "user", "pass");

六、扩展方法库

SilanCore 提供大量链式扩展方法,提升代码简洁性与可读性。

6.1 字符串扩展 StringExtensions

分类 方法 说明
校验 IsMatch 正则匹配判断
格式转换 FirstLetterToUpper/Lower 首字母大小写转换
命名转换 CamelToUnderline / UnderlineToCamel 驼峰↔下划线互转
HTML 处理 HtmlEncode / HtmlDecode HTML 实体编解码
类型转换 ToBoolean / ToInt / ToFloat / ToDateTime 字符串转基本类型
截取 Truncate / SubString / SubStringReverse 字符串截取
正则提取 Match / Matches 正则提取匹配结果
替换 ReplaceAll 全量替换
移除 RemoveAllWhitespace / RemoveStart / RemoveEnd 空白与首尾移除
高亮 Highlight JSON 字符串语法高亮(CSS 类)
string result = "UserName".CamelToUnderline();        // "user_name"
string camel = "user_name".UnderlineToCamel();        // "UserName"
string truncated = "Hello World".Truncate(5);          // "Hello..."
DateTime dt = "2025-06-24 10:30:00".ToDateTime();
string highlighted = jsonStr.Highlight();

6.2 日期时间扩展 DateTimeExtensions

方法 说明
GetFirstDayOfWeek 获取所在周第一天(默认周一)
GetFirstDayOfMonth / GetLastDayOfMonth 获取所在月首末日期
IsWeekend 判断是否为周末
ExtractDate / ExtractTime 提取日期/时间部分
Formate 格式化日期/时间跨度
DateTime firstDay = DateTime.Now.GetFirstDayOfMonth();
bool isWeekend = DateTime.Now.IsWeekend();
string formatted = DateTime.Now.Formate(DateTimeFormatConstants.DateTimeNoFractionSlash);

6.3 对象扩展 ObjectExtensions

方法 说明
Serialize 对象序列化为 JSON(支持格式化、忽略空值、日期格式)
Deserialize JSON 反序列化为强类型对象
DynamicDeserialize JSON 动态反序列化为 JObject/JArray
ActionResult 对象序列化为 IActionResult
Convert 对象通过 JSON 深拷贝转换类型
string json = user.Serialize(formatting: true, ignoreNullValue: true);
UserDto dto = json.Deserialize<UserDto>();
IActionResult result = data.ActionResult();
UserDto copy = original.Convert<UserDto>();

6.4 集合扩展 ListExtensions

分类 方法 说明
校验 IsNullOrEmpty / IsCountGreaterThan 空集合与数量判断
筛选 Filter / FilterIndices 条件筛选与索引查找
转换 Transform / ConvertAll 元素类型转换
排序 SortBy / Shuffle 排序与随机打乱
删除 RemoveAll / RemoveNull 条件删除与空值清理
去重 Distinct 去重
获取 First / End / FirstRange / GetEndRange 首末元素与范围获取
分组 GroupBy / ToDictionary 分组与转字典
分页 Paginate 内存分页
拼接 Join 元素拼接为字符串
克隆 DeepClone 深度克隆(需 ICloneable)
var activeUsers = users.Filter(u => u.isActive);
var grouped = users.GroupBy(u => u.department);
var page = users.Paginate(pageIndex: 0, pageSize: 10);
string names = users.Select(u => u.name).ToList().Join(prefix: "'", suffix: "'");

6.5 其他扩展

扩展类 说明
DictionaryExtensions 字典获取/合并/转换
NameValueCollectionExtensions 键值集合操作
StringBuilderExtensions StringBuilder 链式追加
StreamExtensions 流读写与转换
DatabaseTransactionExtensions 事务提交/回滚/释放
EnvironmentExtensions 环境判断(生产/测试相关)
HttpRequestExtensions HTTP 请求信息提取
LoggerExtensions 日志扩展方法
ReflectionExtensions 反射获取属性/方法/特性

七、特性与常量定义

7.1 特性定义 Attributes

SilanCore 提供表与字段的中英文名特性,用于元数据描述与代码生成。

特性 作用目标 说明
TableChineseNameAttribute Class 表中文名
TableEnglishNameAttribute Class 表英文名
FieldChineseNameAttribute Property 字段中文名
[TableChineseName("用户信息表")]
public class UserDto : BaseIntDto
{
    [FieldChineseName("用户名")]
    public string name { get; set; }
}

7.2 常量定义 Constants

分类 说明
DateTimeFormatConstants 日期时间格式常量(斜杠/横杠/无分隔等)
TimeoutConstants 超时时间常量
EnvironmentConstants 环境标识常量(local/dev/test/uat/prod 等)
FileExtensionConstants 文件扩展名常量
FileUploadTypeConstants 文件上传类型常量
FileDownloadTypeConstants 文件下载类型常量
HttpContentTypeConstants HTTP Content-Type 常量
HttpRequestHeaderConstants HTTP 请求头常量
HttpRequestMethodConstants HTTP 方法常量
HttpResponseStatusCodeConstants HTTP 状态码常量

7.3 枚举定义 Enums

枚举 说明
DatabaseTypeEnum 数据库类型(SqlServer/MySql/Oracle/PostgreSQL)
EmailTypeEnum 邮件类型(内网/外网)
FileTypeEnum 文件类型(XLSX/DOCX/PDF/JPG/ZIP 等)
SerialNumberResetTypeEnum 序列号重置类型

八、接口抽象层

SilanCore 通过接口抽象实现解耦与可测试性,所有核心能力均可替换实现。

接口 说明
IController 控制器接口,定义 HandleResponse 方法规范
IService 服务接口,定义业务操作执行规范
ILog 日志接口,提供 Logger 实例
IJsonConverter JSON 转换器接口,控制属性映射策略
IExcelReader Excel 读取器接口
IExcelWriter Excel 写入器接口
IExcelStyleProvider Excel 样式提供器接口
IExcelDataConverter Excel 数据转换器接口
接口扩展示例
// 自定义 Excel 样式提供器
public class CustomExcelStyleProvider : IExcelStyleProvider
{
    public ICellStyle GetHeaderStyle(IWorkbook workbook) { /* 自定义表头样式 */ }
    public ICellStyle GetBodyStyle(IWorkbook workbook) { /* 自定义正文样式 */ }
}

九、配置参考

9.1 完整配置示例

{
  "InternalEmailServer": { /* 内网邮件配置 */ },
  "ExternalOutEmailServer": { /* 外网发件配置(可选) */ },
  "ExternalInEmailServer": { /* 外网收件配置(可选) */ },
  "ApiErrorEmailMessage": { /* 异常告警配置(可选) */ },
  "AlibabaCloudSms": { /* 短信配置(可选) */ },
  "Hangfire": { /* 定时任务配置(可选) */ },
  "Environment": "prod",
  "DomainUsername": "domainuser",
  "DomainPassword": "domainpassword"
}

9.2 配置说明

  • 核心必需InternalEmailServer(邮件为最小可用集)、Environment
  • 按需开启:其他服务按业务需要选择性配置
  • 异常告警:建议生产环境开启
  • Hangfire:需指定作业数据库连接字符串
  • 网络共享DomainUsername / DomainPassword 用于 SMB/UNC 访问

十、扩展规划

10.1 已规划能力

模块 能力
文件服务 OSS / MinIO / 本地存储统一抽象
缓存服务 Redis 分布式缓存
分布式锁 基于 Redis 的分布式锁
数据访问 通用仓储与工作单元模式
认证授权 OAuth 第三方登录集成
消息队列 RabbitMQ / Kafka 集成
导入导出 Excel / CSV 通用导入导出
系统配置 动态字典与配置中心
操作审计 用户操作日志审计
服务治理 限流、熔断、降级

10.2 版本规划

  • v1.x:基础服务(邮件、短信、定时任务)+ 工具类库 + 扩展方法
  • v2.x:数据与存储服务(文件、缓存、仓储)
  • v3.x:治理与服务(消息队列、限流熔断、审计)

文档版本:v1.1 | 更新日期:2026-06-24

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

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.23 0 7/3/2026
Loading failed