WebApi.Library 1.1.6.1

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

WebApi.Library

Version .NET

WebApi.Library 是一个综合性的 .NET 库,提供 Web API 开发的常用功能封装,包括身份验证、缓存、事件管理、健康检查等。该库基于 Redis 缓存、JWT 身份验证、MySQL 数据库和 OSS 对象存储,旨在简化企业级应用的开发和维护。

注意:这是一个大杂烩库,未来将逐步分离精简以便于维护和升级。

🚀 主要特性

  • 身份验证:基于 JWT 的身份验证,支持角色和权限控制。
  • 缓存管理:Redis 缓存支持,包含异步操作、键前缀配置和多种实现(内存-文件二级缓存)。
  • 事件系统:高性能事件管理,支持异步处理和队列机制。
  • 健康检查:集成健康检查,支持数据库和 Redis 状态监控。
  • Swagger 支持:自动生成 API 文档。
  • 数据库集成:MySQL 支持,通过 Entity Framework Core。
  • 错误日志:ElmahCore 集成,用于错误记录和查看。
  • IP 地址库:基于 IPTools 和 ip2region 的 IP 查询功能。

📦 版本信息

当前版本:1.1.6

主要更新

  • ✅ 支持 .NET 10.0(新增目标框架)。
  • 🔄 更新部分依赖组件版本,确保兼容性和性能。
  • ⚠️ AutoMapper 过期:库中所有 AutoMapper 相关代码已标注为 [Obsolete],不再内置。如需使用,请自行安装 AutoMapper 相关包。作为过渡期目前还没有从项目中移除相关代码(请尽快升级)。
  • 🛠️ 缓存优化:缓存仓库全面异步化,支持 DI 注入、键前缀配置和多种缓存策略(Redis、内存-文件)。
  • 📡 事件服务优化:事件管理系统性能提升,支持并行处理、健壮的异常处理和队列管理。
  • 🔧 其他改进:Swagger 配置修复、代码结构优化和可维护性增强。

⚙️ 配置

在项目根目录的 appsettings.json 中写入默认配置,可在 appsettings.Development.jsonappsettings.Production.jsonappsettings.{EnvironmentName}.json 中覆盖环境特定配置。这些文件无需纳入版本控制。

依赖注入

  • 实现 IAutoLoadConfigurations 的配置类会自动注册到 DI 容器。使用 AutoLoadConfigurationsAttribute 指定配置节名称(默认为类名)。
[AutoLoadConfigurations("Jwt")]
public class JwtSettings : IAutoLoadConfigurations
{
    public string Secret { get; set; }
}
  • 实现 IAutoRegisterRepository 的类自动注册为 Scoped
  • 实现 IAutoRegisterSingleton 的类自动注册为 Singleton

应用启动

使用 WebApplication.Start() 方法自动配置 WebAPI 并注册服务。

public class Program
{
    public static void Main(string[] args)
    {
        WebApplication.Start(
            args: args,
            setupStartOptions: options =>
            {
                // 禁用自动注册依赖注入(默认启用)
                options.AutoRegisterServices = false;
            },
            setupService: (services, configuration, env) =>
            {
                // 配置服务
                services.SetupSwagger("API 名称", "v1", "WebApi.xml", true);
                services.ConfigElmah(env, options => options.Path = "elmah");
                // 缓存配置示例
                services.AddRedisCache("myapp:");
                // 或
                services.AddMemoryFileCache("/path/to/cache", "local:");
            },
            setupApp: app =>
            {
                // 启动后台进程
            }
        );
    }
}

📚 模块说明

🔐 身份验证

基于 JWT 和 Redis 的身份验证系统。

  • Token 结构:Payload 包含 UserIdUserNameRolesUserTypeExpire(短过期时间,支持自动刷新)。
  • 自动续期:Token 在过期前 5 分钟内使用时自动刷新(通过 header 中的 newToken 返回新 Token)。
  • Refresh Token:完全过期后可通过 Refresh Token 获取新 Token,避免重复登录。
  • Token 获取:优先从 Authorization header(Bearer {JWT_TOKEN}),其次从 Query 参数 ?token={JWT_TOKEN}

内置策略:

  • Backend:检查用户类型是否为后台管理员。
  • SystemUser:用于内部微服务调用。
[Authorize(Policy = CommonConsts.Policy.Backend)]  // 后台权限
[Authorize(Policy = CommonConsts.Policy.System)]   // 系统内部
[Authorize]                                        // 登录用户
[Authorize(Roles = "VIP")]                         // VIP 角色

💾 缓存管理

支持 Redis 和内存-文件二级缓存,全面异步化。

  • 异步操作:所有方法支持 async/await,提高并发性能。
  • 键前缀:可配置前缀,避免键冲突。
  • DI 支持:通过扩展方法轻松注入。
  • 缓存策略:Redis 为主,内存-文件为兜底。
// 注入示例
services.AddRedisCache("app:");  // Redis 缓存
services.AddMemoryFileCache("/cache", "mem:");  // 内存-文件缓存

// 使用
await cache.SetAsync("key", data, 3600);
var result = await cache.GetAsync<MyType>("key");

📡 事件系统

高性能事件管理,支持异步和队列处理。

  • 异步触发:并行处理多个处理器。
  • 队列支持:后台服务处理事件队列,支持重试和并发控制。
  • 健壮性:改进异常处理和日志记录。
// 注册事件
eventService.On("eventKey", async (data) => { /* 处理 */ });

// 触发事件
await eventService.FireAsync("eventKey", data);

🩺 健康检查

集成 ASP.NET Core 健康检查。

  • 端点/healthz/alive(存活检查)、/healthz/ready(就绪检查)。
  • 检查项:数据库、Redis 等。
services.SetupHealthCheck(builder =>
{
    builder.AddDbContextCheck<MyDbContext>("Db", tags: new[] { "ready" });
    builder.AddRedisCheck();
});

📋 错误日志 (ElmahCore)

使用 ElmahCore 记录和查看错误日志。

  • 访问路径/elmah(开发环境)或 /elmah?token={JWT_TOKEN}(生产环境)。
services.ConfigElmah(env, options => options.Path = "elmah");

🌐 IP 地址库

基于 IPTools 和 ip2region 的 IP 查询。

services.SetupIpTools(Path.Combine(env.ContentRootPath, "Assets", "ip2region.db"), useMemoryCache: true);

📋 依赖库

库名 描述 版本
JWT 身份验证 8.14.0
Redis (xBei.Redis.Extension) 缓存存储 1.0.2
ElmahCore 错误日志 2.1.2
Swashbuckle.AspNetCore Swagger 10.0.0
Pomelo.EntityFrameworkCore.MySql MySQL ORM 9.0.0
AutoMapper 对象映射(已过期) 14.0.0

注意:AutoMapper 相关功能已标记为过期,请考虑迁移到其他映射库或手动实现。

🛠️ SDK 要求

📄 许可证

请查看 LICENSE.txt 文件。

🤝 贡献

欢迎提交 Issue 和 Pull Request 以改进此库。


*最后更新:2025-11-12

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

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.1.6.1 250 12/19/2025
1.1.5.6 212 4/27/2025
1.1.5.1 176 12/30/2024