# basestandard **Repository Path**: one996/basestandard ## Basic Information - **Project Name**: basestandard - **Description**: c#代码标准库 - **Primary Language**: C# - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-05-16 - **Last Updated**: 2026-05-16 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # BaseStandard 一款面向 .NET 9 的通用标准库,提供生产级的基础设施组件,涵盖函数式类型、扩展方法、数据校验、序列化、缓存、日志、弹性容错、安全加密等 27 个功能模块,以及 40+ 应用演示项目和 37 个 Azure 云服务对接项目。开箱即用,单元测试覆盖率达 95%+。 ## 模块概览(src/) | 模块 | 命名空间 | 说明 | |------|---------|------| | **Core** | `BaseStandard.Core` | Result/Maybe/Either 函数式类型、Guard 参数守卫 | | **Extensions** | `BaseStandard.Extensions` | String/Collection/DateTime/Enum 等扩展方法 | | **Utilities** | `BaseStandard.Utilities` | 身份证/手机号/密码强度校验、SnowflakeId/Nanoid/ULID、对象映射 | | **Exceptions** | `BaseStandard.Exceptions` | AppException 异常体系、ErrorResponse 统一响应 | | **Serialization** | `BaseStandard.Serialization` | JSON/XML 封装、DateTime/Long/Enum 自定义转换器 | | **Testability** | `BaseStandard.Testability` | ISystemClock/IFileSystem/IGuidProvider 抽象 + Mock 实现 | | **Logging** | `BaseStandard.Logging` | ILoggerService 抽象、ConsoleLogger/NullLogger、LogContext、LogHelper | | **Caching** | `BaseStandard.Caching` | ICacheProvider 抽象、MemoryCacheProvider、NoopCacheProvider | | **Resilience** | `BaseStandard.Resilience` | RetryPolicy、CircuitBreaker、Bulkhead、TimeoutPolicy、PolicyPipeline | | **Data** | `BaseStandard.Data` | PagedResult、IRepository、IUnitOfWork、BaseEntity、QueryBuilder | | **Security** | `BaseStandard.Security` | AES/RSA 加密、MD5/SHA256/SHA512/PBKDF2 哈希、数据脱敏 | | **DependencyInjection** | `BaseStandard.DependencyInjection` | `AddBaseStandard()` 一键注册所有服务 | | **BackgroundServices** | `BaseStandard.BackgroundServices` | BackgroundServiceBase、PeriodicBackgroundService、QueueBackgroundService、CronJobService | | **Expressions** | `BaseStandard.Expressions` | PredicateBuilder 动态查询、ExpressionHelper | | **Compression** | `BaseStandard.Compression` | Gzip/Brotli 压缩、Base64/Base64Url/Hex 编解码 | | **Environment** | `BaseStandard.Environment` | RuntimeInfo 运行时信息、MimeTypes MIME 映射 | | **NaturalSort** | `BaseStandard.NaturalSort` | 自然排序(item1 → item2 → item10) | | **DesignPatterns** | `BaseStandard.DesignPatterns` | Singleton、Disposable、StrategyResolver、ChainOfResponsibility、ObserverManager | | **Aspects** | `BaseStandard.Aspects` | [ChineseIdCard]、[ChinesePhone]、[StrongPassword]、[RequiredIf] 验证属性 | | **Concurrency** | `BaseStandard.Concurrency` | AsyncEnumerable 扩展(WhereAsync/SelectAsync/ToListAsync) | | **Networking** | `BaseStandard.Networking` | HTTP 客户端封装、邮件发送 | | **FileStorage** | `BaseStandard.FileStorage` | 文件存储抽象、本地文件提供程序 | | **Localization** | `BaseStandard.Localization` | JSON 本地化、多语言支持 | | **Streams** | `BaseStandard.Streams` | Stream 扩展、AsyncEnumerable 扩展、CancellationToken 工具 | | **ValidationAttrs** | `BaseStandard.ValidationAttrs` | 验证属性集合 | | **Versioning** | `BaseStandard.Versioning` | 语义版本、版本范围 | | **MimeTypes** | `BaseStandard.MimeTypes` | MIME 类型完整映射、文件头签名检测 | ## 快速开始 ### 安装 ```bash dotnet add package BaseStandard.DependencyInjection ``` ### 注册服务 ```csharp using BaseStandard.DependencyInjection; var services = new ServiceCollection(); services.AddBaseStandard(options => { options.UseConsoleLogger = true; options.MinimumLogLevel = LogLevel.Information; options.UseMemoryCache = true; options.CacheDefaultMinutes = 30; }); ``` ## 使用示例 ### Result 函数式错误处理 ```csharp using BaseStandard.Core.Results; Result Divide(int a, int b) { if (b == 0) return Error.Failure("DIVISION_BY_ZERO", "除数不能为0"); return a / b; } var result = Divide(10, 2) .OnSuccess(x => Console.WriteLine(x)) .OnFailure(err => Console.WriteLine(err.Message)); ``` ### Guard 参数守卫 ```csharp using BaseStandard.Core.Guard; void Process(string name, int age) { Guard.ThrowIfNullOrWhiteSpace(name); // 自动捕获参数名 Guard.ThrowIfLessThan(age, 18); // ArgumentOutOfRangeException } ``` ### 弹性容错 ```csharp using BaseStandard.Resilience; var retry = new RetryPolicy(maxRetries: 3, baseDelay: TimeSpan.FromMilliseconds(100)); await retry.ExecuteAsync(async () => { var data = await httpClient.GetAsync("https://api.example.com/data"); return data; }); var cb = new CircuitBreaker(failureThreshold: 5, openTimeout: TimeSpan.FromSeconds(30)); cb.Execute(() => DoSomething()); ``` ### 数据脱敏 ```csharp using BaseStandard.Security; DataMaskHelper.MaskEmail("user@example.com"); // "u****@example.com" DataMaskHelper.MaskPhone("13812345678"); // "138****5678" DataMaskHelper.MaskIdCard("110101199001011237"); // "1101**********1237" ``` ### 密码哈希 ```csharp using BaseStandard.Security; var (hash, salt) = HashingHelper.HashPassword("mypassword"); bool valid = HashingHelper.VerifyPassword("mypassword", hash, salt); // true ``` ### 验证属性 ```csharp using BaseStandard.Aspects; public class RegisterRequest { [ChineseIdCard] public string IdCard { get; set; } [ChinesePhone] public string Phone { get; set; } [StrongPassword(MinLength = 8)] public string Password { get; set; } [RequiredIf(nameof(HasSubscription), true)] public string Email { get; set; } } ``` ## 应用演示项目(apps/) 40 个应用演示项目,覆盖 .NET 全技术栈: ### Web 服务端 | 项目 | 技术栈 | 说明 | |------|--------|------| | BaseStandard.Api | ASP.NET Core Web API | RESTful API + JWT + Swagger | | BaseStandard.MinimalApi | Minimal API | .NET 9 简洁 API | | BaseStandard.Mvc | ASP.NET Core MVC | Controller + Razor 视图 | | BaseStandard.RazorPages | Razor Pages | 页面驱动开发模式 | | BaseStandard.Grpc | gRPC | Protobuf + 双向流 | | BaseStandard.SignalR | SignalR | WebSocket 实时通信 | ### Blazor 全栈 | 项目 | 技术栈 | 说明 | |------|--------|------| | BaseStandard.BlazorServer | Blazor Server | 交互式 UI + SignalR | | BaseStandard.BlazorWasm | Blazor WebAssembly | 浏览器端 C# SPA | | BaseStandard.BlazorHybrid | MAUI Blazor | 嵌入原生跨平台应用 | | BaseStandard.FluentBlazor | Fluent UI Blazor | 微软官方 Fluent 组件 | ### 中间件与扩展 | 项目 | 技术栈 | 说明 | |------|--------|------| | BaseStandard.HealthChecks | Health Checks | 自定义健康检查 + UI | | BaseStandard.RateLimiting | Rate Limiting | 固定窗口/令牌桶/并发限制 | | BaseStandard.OutputCaching | Output Caching | 响应缓存策略 | | BaseStandard.Yarp | YARP | 反向代理/负载均衡 | | BaseStandard.WebHooks | WebHooks | GitHub/Azure DevOps WebHook 接收 | | BaseStandard.OData | OData | OData 查询/筛选/展开/分页 | | BaseStandard.NativeAot | Native AOT | 原生提前编译发布 | ### 桌面与跨平台 | 项目 | 技术栈 | 说明 | |------|--------|------| | BaseStandard.Wpf | WPF | MVVM + Material Design | | BaseStandard.WinForms | WinForms | DataGridView + 传统桌面 | | BaseStandard.WinUI3 | WinUI 3 | 现代 Windows 原生 UI | | BaseStandard.Maui | .NET MAUI | 跨平台原生应用 | | BaseStandard.Win2D | Win2D | 2D 图形绘制 | ### 云与 AI | 项目 | 技术栈 | 说明 | |------|--------|------| | BaseStandard.AzureFunctions | Azure Functions | 多种触发器 + 无服务器 | | BaseStandard.SemanticKernel | Semantic Kernel | AI 编排框架 | | BaseStandard.MlNet | ML.NET | 机器学习训练/预测 | | BaseStandard.KernelMemory | Kernel Memory | RAG 知识库 | | BaseStandard.OpenXml | Open XML SDK | Word/Excel 文档生成 | ### 身份与安全 | 项目 | 技术栈 | 说明 | |------|--------|------| | BaseStandard.Identity | ASP.NET Core Identity | 注册/登录/角色/Claims | | BaseStandard.MsalEntraId | MSAL + Entra ID | OAuth2/Microsoft Graph | ### 分布式与 CLI | 项目 | 技术栈 | 说明 | |------|--------|------| | BaseStandard.Orleans | Microsoft Orleans | 虚拟 Actor 框架 | | BaseStandard.Aspire | .NET Aspire | 分布式应用编排 | | BaseStandard.CommandLine | System.CommandLine | CLI 解析/命令绑定 | | BaseStandard.PowerShell | PowerShell SDK | PowerShell 命令执行 | ### 数据访问 | 项目 | 技术栈 | 说明 | |------|--------|------| | BaseStandard.EfCore | EF Core + SQLite | CodeFirst/迁移/CRUD | | BaseStandard.Dapper | Dapper | 微型 ORM 查询 | ### 游戏与高级技术 | 项目 | 技术栈 | 说明 | |------|--------|------| | BaseStandard.MonoGame | MonoGame | 2D/3D 游戏框架 | | BaseStandard.Godot | Godot + C# | Godot 引擎 C# 脚本 | | BaseStandard.SourceGenConsumer | Source Generators | 源生成器消费示例 | ### 后台服务 | 项目 | 技术栈 | 说明 | |------|--------|------| | BaseStandard.Worker | .NET Worker | 后台服务(Windows Service/systemd) | | BaseStandard.Cli | Console | 命令行工具 | ## Azure 云服务演示(azure/) 37 个 Azure 云服务对接演示项目: ### 存储(5) Blob Storage · Queue Storage · Table Storage · File Storage · Data Lake Storage ### 数据库(6) Cosmos DB · SQL Database · Redis Cache · MySQL · PostgreSQL · Key Vault Keys ### 消息与事件(5) Service Bus · Event Hubs · Event Grid · Notification Hubs · App Configuration ### IoT(5) IoT Hub · Device Provisioning (DPS) · IoT Central · IoT Edge · Azure Maps ### AI + 认知服务(7) Text Analytics · Translator · Speech · Face API · Document Intelligence · AI Search · Content Safety · Image Analysis · Azure OpenAI ### 安全与配置(4) Key Vault Secrets · Key Vault Certificates · Key Vault Keys · Feature Flags ### 监控与管理(4) Application Insights · Log Analytics · Resource Manager · App Configuration ## 项目结构 ``` BaseStandard/ ├── src/ # 源项目(27 个) │ ├── BaseStandard.Core/ # 核心:Result、Maybe、Guard │ ├── BaseStandard.Extensions/ # 扩展方法 │ ├── BaseStandard.Utilities/ # 工具类 │ └── ... ├── apps/ # 应用演示(40 个) │ ├── BaseStandard.Api/ # ASP.NET Core Web API │ ├── BaseStandard.Orleans/ # Orleans 虚拟 Actor │ ├── BaseStandard.Aspire/ # .NET Aspire 编排 │ └── ... ├── azure/ # Azure 云服务(37 个) │ ├── BaseStandard.Azure.BlobStorage/ │ ├── BaseStandard.Azure.CosmosDb/ │ └── ... ├── tests/ # 测试项目(27 个) │ ├── BaseStandard.Core.Tests/ │ └── ... ├── docs/ # 文档 ├── Directory.Build.props # 统一编译配置 ├── BaseStandard.sln # src 解决方案 └── apps/BaseStandard.Apps.sln # apps 解决方案 ``` ## 技术栈 - **.NET**: .NET 9, C# 12 - **测试**: xUnit 2.9.2, FluentAssertions 7.0, NSubstitute 5.3, coverlet 6.0 - **特性**: 源生成器 (GeneratedRegex)、函数式类型 (readonly struct)、CallerArgumentExpression - **云 SDK**: Azure SDK for .NET - **AI/ML**: ML.NET, Semantic Kernel, Kernel Memory - **游戏**: MonoGame, Godot + C# - **桌面**: WPF, WinForms, WinUI 3, MAUI ## 编译与测试 ```bash # 编译全部 dotnet build # 编译应用项目 dotnet build apps/BaseStandard.Apps.sln # 运行全部测试 dotnet test # 查看测试覆盖率 dotnet test --collect:"XPlat Code Coverage" reportgenerator -reports:"**/coverage.cobertura.xml" -targetdir:"coverage" ``` ## 设计原则 - 每个模块独立可引用,模块间通过 DI 项目统一注册 - 函数式类型使用 `readonly struct` 保证零开销 - 扩展方法遵循函数式风格,支持链式调用 - 所有公开 API 都包含完整单元测试 - 安全模块使用 `CryptographicOperations.FixedTimeEquals` 防时序攻击 - 应用项目遵循各框架官方最佳实践