LuBan.Web.Core 2026.11.9.1

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

English | 中文

LuBan.Web.Core

作者: yswenli | 联系邮箱: yswenli@outlook.com | 代码仓库: https://github.com/yswenli/luban-framework

一行代码启动企业级 API 服务——JWT、Swagger、多租户、审批流、实时通信全内置。


Related Projects: LuBan.Framework | LuBan.Common | LuBan.Logging | LuBan.Orm | LuBan.Redis | LuBan.Service | LuBan.EventBus | LuBan.ApprovalFlow | LuBan.Wechat | LuBan.AIAgent | LuBan.AIFlow


为什么选择 LuBan.Web.Core?

你是否厌倦了每个新项目都要重复配置 JWT 认证、Swagger 分组、全局异常处理、统一响应格式、多租户数据库路由?
LuBan.Web.Core 把这些"脏活累活"全部封装为一行启动代码,让你专注于业务逻辑。


快速预览

// Program.cs — 只需两行即可启动完整 API 服务
WebApp.RunWebHost(args);

// 或异步方式
await WebApp.RunWebHostAsync(args);

就这么简单。框架会自动读取 appsettings.json 中的 HostingOptions 配置,完成 DI 注册、中间件管道搭建、数据库初始化、后台任务启动等全部工作。


技术栈 & 依赖

类别 组件 说明
运行时 .NET 10.0 ASP.NET Core 最小宿主
缓存 LuBan.Redis Redis 分布式缓存 & 锁
系统服务 Microsoft.Extensions.Hosting.Systemd / Microsoft.Extensions.Hosting.WindowsServices 支持注册为系统服务
审批流 LuBan.ApprovalFlow 内置审批流引擎
报表导出 LuBan.Reporting Excel/CSV 导出
云存储 LuBan.CloudStorage 对象存储集成
日志 LuBan.Logging 基于 Microsoft.Extensions.Logging 的文件日志 Provider,支持 100MB/跨天滚动
公共基础 LuBan.Common 统一响应(Result / Success / Fail)、分页、加解密与通用工具
数据访问 LuBan.Orm 实体基类与仓储基类,供 DbRepository<TEntity> 继承使用
后台任务 LuBan.Service 作业宿主、配置与日志(JobsController 的服务端支撑)
AI Agent LuBan.AIAgent 连接器抽象与通用外部 MCP 接入
语音 LuBan.Speech 语音识别/合成能力

安装

dotnet add package LuBan.Web.Core

配置

在 appsettings.json 中添加核心配置:

{
  "HostingOptions": {
    "ServiceName": "我的API服务",
    "Domain": "https://api.example.com",
    "EnableRedisCache": true,
    "EnableBackgroundJob": true,
    "EnableHealthCheck": true,
    "EnableVideoThumbnail": false,
    "AppOptions": {
      "Urls": [ "http://0.0.0.0:5000" ],
      "StartPath": "/swagger"
    },
    "NacosConfig": {
      "ServerAddresses": [ "http://nacos:8848" ],
      "Namespace": "production"
    }
  }
}

LuBan Agent 接入

框架在标准启动链(WebApp.RunWebHost)中会自动尝试注册 LuBan Agent,配置按以下顺序解析:

  1. db_config 表中 Code = sys-luban-framework:aiagent 的记录,Value 为与 LuBanAgent 节结构一致的 JSON;
  2. 上述记录不存在时,回退宿主配置(appsettings.json 的 LuBanAgent 节、环境变量);
  3. 两处都没有、或内容不完整/不合法 → 不启用,站点照常启动,控制台输出一条黄字原因。
{
  "LuBanAgent": {
    // 绝对路径,或相对站点内容根(ContentRootPath,即网站根目录)的路径
    "WorkspaceRoot": ".",
    // 可省略;省略时取 Models 数组第一项
    "DefaultModel": "deepseek:deepseek-chat",
    "Models": [
      {
        "Provider": "deepseek",
        "Model": "deepseek-chat",
        "ApiKey": "sk-***",
        // 可省略,但仅当 Provider 有内置默认地址时安全(deepseek/openai/kimi/ollama 等);
        // 自建网关、代理或内置表外的 Provider 必须显式配置,否则会落到 OpenAI 默认端点
        "BaseUrl": "https://api.deepseek.com/v1/"
      }
    ]
  }
}

校验口径:

  • Models 为数组,每项 Provider 非空(大小写不敏感;内置表之外的自定义 Provider 也允许),Model / ApiKey 非空,BaseUrl 若给出必须是合法 http(s) 地址;
  • 内置 Provider 可省略 BaseUrl,省略时取内置地址(见 ProviderDefaults);内置项本身没有内置地址(如 azure / claude / gemini)时 Endpoint 为 null,OpenAI SDK 会落到 https://api.openai.com/v1/,并输出一条 ChatClientFactoryWarning;
  • 内置表之外的 Provider(自建网关、代理、未收录厂商)必须显式配置 BaseUrl,如 "Provider": "internal-llm" 配 "BaseUrl": "http://10.10.0.147:11689/v1";缺 BaseUrl 的会在启动期判定「不启用」并给出原因,不会静默打到 OpenAI 默认端点;
  • 同一 Provider 可配置多个模型,但 ApiKey / BaseUrl 必须一致,否则该 Provider 不注册;
  • DefaultModel 可省略(省略取数组第一项);一旦给出,必须是 provider:model 且命中 Models 中某项;
  • WorkspaceRoot 支持绝对路径与相对路径:相对值以站点 ContentRootPath 为基准,非 Web 宿主(如单元测试)回退到程序目录; 注意 Windows 上以 / 开头的值算绝对路径(/aiagent → 当前盘根 D:\aiagent),要落站点内请写 aiagent 或 ./aiagent;

升级提示:旧版的扁平对象写法("Models": { "Provider": ... })不再支持,需改为数组。

关闭方式:删除 LuBanAgent 节且不配置 db_config 记录即可(不存在"只关一半"的开关)。Agent 初始化失败只降级为不启用,不会导致 Web 应用启动失败。


功能全景

启动入口

API 说明
WebApp.RunWebHost(args) 同步启动 Web 服务
WebApp.RunWebHostAsync(args) 异步启动 Web 服务
WebApp.HostingOptions 获取全局配置
WebApp.HttpContext 静态获取当前请求上下文
WebApp.User 静态获取当前 JWT 用户
WebApp.ServiceCache 获取缓存服务实例
WebApp.RootPath 站点根目录路径
WebApp.GetPhysicalPath(...) 获取物理文件路径

控制器继承体系

框架提供 6 种基类控制器,覆盖不同接入场景:

BaseApiController       — JWT 认证,路由 api/,Swagger 分组 default
├── BaseAdminController — 管理端,路由 api/admin/,分组 admin,需角色授权
├── BaseMobileController— 移动端,路由 api/mobile/,分组 mobile
├── BaseInternalController — 内部接口,路由 api/internal/,分组 internal
└── BaseOpenController  — 开放接口,路由 api/open/,分组 open,匿名 + 防重放 + OpenAPI 令牌

BaseWebController       — Cookie 认证,管理后台 Web 页面

认证 & 授权

  • JWT 认证:JwtConfigureService 自动配置,SessionUser 获取当前用户
  • 角色访问控制:[ForbiddenAccess] 限制管理端、[AllowAccess] 放行移动端/内部接口
  • Open API 认证:[OpenApiAccess] 基于 refresh/access token 的开放接口鉴权
  • 内部服务接口认证:[InternalApiAccess] 只需传入 Bearer {RefreshToken},供内部服务间调用,无需走完整 AccessToken 流程
  • Cookie Web 认证:[WebLoginAuth] 用于管理后台页面

统一响应格式

所有 API 返回统一结构(由 ApiResultConvertionAttribute 自动包装):

{
  "code": 200,
  "type": "Success",
  "message": "OK",
  "result": { ... },
  "time": "2026-10-30 16:00:00"
}
  • type 取 Success / Fail,message 成功时为 OK;
  • time 为 yyyy-MM-dd HH:mm:ss 格式的字符串(由 DateTimeJsonConverter 统一序列化);
  • extras 默认为 null,序列化时忽略 null 字段,因此通常不会出现,可省略。

核心中间件 & 过滤器

组件 说明
ErrorHandlingMiddleware 全局异常捕获,统一错误响应
OnlineUserMiddleware 在线用户统计与管理
AraParameterFilterAttribute 防重放攻击(时间戳 + 签名)
DistributedLockAttribute Redis 分布式锁,防止并发重复操作;构造参数 (lockName, variableType, variableName, timeout=10000ms, maxRetries=5, dbIndex=0),变量段由 EnumVariableType(Query/Form/Route/Header/Cookie 按 VariableName 取值,ContextUser 取当前用户 ID)拼到锁 Key 后
OutputCacheAttribute 接口输出缓存
CacheableAttribute 声明式缓存
CacheClearAttribute 缓存清除
IPWhiteListFilterAttribute IP 白名单过滤
DataScopePermissionFilter 数据权限(本人/部门/组织/全部),静态辅助类,非过滤器特性,用于生成/校验数据权限范围
IgnoreDataScopePermissionAttribute 挂在类或方法上跳过数据权限校验
InputArgsValidateActionFilterAttribute 入参自动校验

多租户数据库

DbRepository<TEntity> 自动从 JWT 中解析租户 ID,路由到对应数据库:

// 自动根据当前用户租户选择数据库连接
var repo = new DbRepository<SysUser>();
var users = await repo.GetListAsync();

// 切换实体仓储
var userRepo = repo.Change<SysRole>();

Swagger 分组文档

自动生成 5 组 API 文档:default、admin、mobile、internal、open,支持 Markdown 导出和 JS SDK 生成。

SignalR 实时通信

内置 CommonHub,支持 IHubClient / IHubServer 接口和 SimpleClient 快速接入。

其他能力

  • 后台任务:JobsController + JobServiceLoader 管理定时任务,支持运行时动态更新 Cron 表达式
  • 健康检查:HealthCheckService 支持企业微信机器人告警
  • SSE 流式输出:SseStream 服务端推送;SseEventWriter / SseEventPump 写命名事件帧(event: <name> + 单行 JSON data:)并在空闲时发注释心跳,不依赖 WebApp.HttpContext,便于单测
  • Agent 会话归属:WebAgentSessionRegistry(LuBan.Web.Core.AIAgent)按登录用户维护「最后一次会话」并校验会话归属,避免单例 ISessionManager 的进程级指针被多用户互相覆盖
  • 文件上传下载:UploadFileUtil / DownloadFileUtil / ExtraFileController
  • 图形验证码:内置验证码生成
  • API 压测:CommonController.StressTest
  • 系统服务部署:支持 Windows Service 和 systemd

后台任务 Cron 管理

JobsController 提供以下端点(全部为 [HttpPost]),支持运行时查询和动态更新任务配置:

方法 端点 说明
POST api/admin/Jobs/GetJobCron?name=xxx 查询任务的 Cron 表达式
POST api/admin/Jobs/GetJobNextOccurrence?name=xxx 查询任务的下一次执行时间
POST api/admin/Jobs/GetJobConfigs 查询全部作业配置
POST api/admin/Jobs/UpdateJobConfig?name=xxx&cron=...&isEnabled=...&remark=... 更新作业配置:Cron 变更即时生效,isEnabled 变更会启停作业

参数均为查询串/表单绑定(UpdateJobConfig(name, cron, isEnabled, remark),后三个可空)。

Cron 表达式为 6 段秒级格式(秒 分 时 日 月 周),使用 Cronos 解析。


代码示例

自定义业务控制器

// 管理端接口
public class UserController : BaseAdminController
{
    [HttpGet]
    public async Task<ApiResult> GetList()
    {
        var repo = new DbRepository<SysUser>();
        var list = await repo.GetListAsync();
        return Success(list);
    }
}

// 移动端接口
public class OrderController : BaseMobileController
{
    [HttpPost]
    // 锁 Key = "order" + "_" + 查询参数 userId 的值,如 order_1001
    [DistributedLock("order", EnumVariableType.Query, "userId", timeout: 5000)]
    public async Task<ApiResult> CreateOrder([FromBody] OrderInput input)
    {
        // 业务逻辑
        return Success();
    }
}

// 开放接口(匿名访问 + 防重放 + OpenAPI 令牌)
public class DataSyncController : BaseOpenController
{
    [HttpPost]
    public async Task<ApiResult> SyncData([FromBody] SyncInput input)
    {
        return Success();
    }
}

// 内部服务接口(只需 Bearer {RefreshToken})
public class InternalApiController : BaseInternalController
{
    [InternalApiAccess]
    [HttpPost]
    public async Task<ApiResult> GetData([FromBody] GetDataInput input)
    {
        // 无需 AccessToken,直接使用 RefreshToken 认证
        return Success();
    }
}

注册启动事件

WebApp.OnStarted += () =>
{
    Console.WriteLine("服务已启动,执行自定义初始化...");
};

WebApp.RunWebHost(args);

命令行参数

# 指定监听地址
dotnet run --urls "http://0.0.0.0:5000;http://0.0.0.0:5001"

# 指定 FFmpeg 路径(启用视频缩略图)
dotnet run --ffmpeg "c:/bin/ffmpeg.exe"

# 指定运行环境
dotnet run --environment Production

小贴士

  1. 启动前检查:确保 appsettings.json 中 HostingOptions 配置完整,特别是 ServiceName、Domain、AppOptions.Urls
  2. 多租户:JWT 中需包含 TenantId Claim,否则默认使用主库
  3. 开放接口:BaseOpenController 同时要求 [AllowAnonymous] + [OpenApiAccess] + [AraParameterFilter],缺一不可
  4. 内部服务接口:使用 [InternalApiAccess] 标签时,只需传入 Bearer {RefreshToken},无需获取 AccessToken
  5. 后台任务:通过 BackgroundJobNames 可精确控制启用哪些后台任务,空列表则全部启用
  6. 审批流联动:当 ApprovalFlowOptions.AutoApproval = true 时,FlowEngine 会随服务自动启停

许可证

Copyright (c) yswenli.

Licensed under the Apache License 2.0.

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 (1)

Showing the top 1 NuGet packages that depend on LuBan.Web.Core:

Package Downloads
LuBan.Wechat

LuBan Framework中微信对接相关业务核心项目

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2026.11.9.1 111 11/9/2026
2026.11.2.1 135 11/2/2026
2026.10.27.1 132 10/27/2026
2026.10.23.1 112 10/23/2026
2026.10.20.1 124 10/20/2026
2026.10.9.1 112 10/9/2026
2026.10.8.1 118 10/8/2026
2026.9.22.1 122 9/22/2026
2026.9.21.1 128 9/21/2026
2026.9.20.1 143 9/20/2026
2026.9.18.1 126 9/18/2026
2026.9.16.1 133 9/16/2026
2026.9.11.1 130 9/11/2026
2026.9.10.2 152 9/10/2026
2026.9.10.1 134 9/10/2026
2026.9.8.2 147 9/8/2026
2026.9.8.1 141 9/8/2026
2026.9.7.1 139 9/7/2026
2026.9.4.2 153 9/4/2026
2026.9.4.1 148 9/4/2026
Loading failed

LuBan Framework中api核心功能项目,基于aspnetcore集成di、jwt、swagger、codefirtst、支持多种常见数据库、nacos配置中心、统一接口回复参数、全局异常捕获、全局接口日志、防重放攻击、图形验证码、快捷上下文对象、上传下载、数据导入导出等功能