BugFree.Controllers.Core 1.2.2026.807-beta0945

This is a prerelease version of BugFree.Controllers.Core.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package BugFree.Controllers.Core --version 1.2.2026.807-beta0945
                    
NuGet\Install-Package BugFree.Controllers.Core -Version 1.2.2026.807-beta0945
                    
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="BugFree.Controllers.Core" Version="1.2.2026.807-beta0945" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BugFree.Controllers.Core" Version="1.2.2026.807-beta0945" />
                    
Directory.Packages.props
<PackageReference Include="BugFree.Controllers.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 BugFree.Controllers.Core --version 1.2.2026.807-beta0945
                    
#r "nuget: BugFree.Controllers.Core, 1.2.2026.807-beta0945"
                    
#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 BugFree.Controllers.Core@1.2.2026.807-beta0945
                    
#: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=BugFree.Controllers.Core&version=1.2.2026.807-beta0945&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=BugFree.Controllers.Core&version=1.2.2026.807-beta0945&prerelease
                    
Install as a Cake Tool

BugFree.Controllers.Core

BugFree 的 ASP.NET Core 控制器基础库,提供统一响应、XCode 实体 CRUD、可组合操作能力、配置控制器、CORS、响应压缩、API 版本控制、IP 访问控制和安全响应头等基础设施。

NuGet License


核心能力

📦 统一控制器基类

  • BugFreeController 继承 ControllerBase,统一应用 [Authorize][ApiController] 和版本化 API 路由。
  • 默认路由为 api/[area]/v{version:apiVersion}/[controller]/[action]
  • 内置 Success() / Fail() / Unauthorized() 及对应异步封装。
  • 通过 IResponseService 替换响应构建策略;未注册时自动使用默认实现。

🧩 可组合实体控制器

  • EntityController<TEntity, TModel> 在单一基类中提供 QueryGetAddUpdateUpsertDelete
  • 基于 BugFree.XCode.Extensions 与 XCode ORM;TEntity 必须继承 BugFreeEntity<TEntity> 并实现 IEntity<TModel>
  • ExposeEntityActionsAttribute 可按控制器选择开放的操作,未开放的操作不会进入 MVC 路由和 API Explorer。
  • EntityActions 是标志枚举,支持预设值 ReadOnlyEditableAll,也支持任意按位组合。
  • 不使用 ExposeEntityActionsAttribute 时,六个标准操作全部开放;未标记 EntityActionAttribute 的自定义 Action 不受能力筛选影响。

⚙️ 配置控制器

  • ConfigController<TConfig> 基于 BugFree.Configuration 提供 Get / Save 端点。
  • TConfig 必须继承 Config<TConfig> 并具有无参构造函数。

🛡️ 安全中间件

中间件 功能
IpAccessControlMiddleware 支持单 IP、CIDR、IP 范围和动态评估器;当前执行顺序为 Deny → Allow → 默认放行
SecurityResponseHeaderMiddleware 根据配置注入 CSP、HSTS、X-Frame-Options、Permissions-Policy 等响应头,并在最后移除指定头

📋 统一响应模型

  • Response + ResponseCode 标准化响应码、消息、业务数据和运行时信息。
  • RunTimeContext 记录查询次数、执行次数、耗时和 SQL 列表。

🔧 扩展方法

  • AddCoreService() 注册内存缓存、CORS、Gzip 响应压缩、API 版本控制和 API Explorer。
  • AddBugFreeJsonOptions() 应用统一 JSON 序列化选项,也可传入自定义配置委托。
  • GetRemoteIpAddress() / GetRemoteIp() 解析代理头并回退到连接远端地址。
  • GetRawUri() 可按代理协议头还原原始请求 URI。

📐 配置选项(基于 BugFree.Configuration,支持热更新)

配置类 配置节点 说明
AccessDecisionRulesOptions AccessDecisionRules IP 访问控制规则
CorsOriginRulesOptions CorsOriginRules CORS 域名白名单
ResponseHeaderOptions ResponseHeader 安全响应头、报告端点和待移除响应头配置
HeaderSignatureOptions HeaderSignature 请求头签名字段与时间戳容差配置模型
PageOptions Page 分页参数
RedisOptions Redis Redis 连接配置

目标框架

  • .NET 8.0
  • .NET 10.0

项目通过 FrameworkReference 使用 Microsoft.AspNetCore.App,并针对不同目标框架引用对应版本的 JWT 认证与 API 版本浏览组件。


安装

dotnet add package BugFree.Controllers.Core

或通过 NuGet 包管理器搜索 BugFree.Controllers.Core


快速开始

1. 注册服务和中间件

Program.cs 中:

using BugFree.Controllers.Core.Middleware;
using BugFree.Controllers.Extensions;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers()
    .AddBugFreeJsonOptions();

// 内存缓存、CORS、Gzip、API 版本控制和 API Explorer
builder.Services.AddCoreService();

var app = builder.Build();

app.UseResponseCompression();
app.UseCors();
app.UseMiddleware<IpAccessControlMiddleware>();
app.UseMiddleware<SecurityResponseHeaderMiddleware>();

// 认证与授权由宿主应用按实际方案注册并加入管道。
app.MapControllers();

app.Run();

AddCoreService() 负责注册服务,UseResponseCompression()UseCors() 和两个安全中间件仍需由宿主显式加入请求管道。由于 BugFreeController 带有 [Authorize],宿主还必须配置可用的认证与授权方案。

2. 创建完整实体控制器

先准备 XCode 实体和输入输出模型。泛型必须满足以下关系:

// TEntity : BugFreeEntity<TEntity>, IEntity<TModel>, new()
// IEntity<TModel>.Copy(TModel model) 负责模型到实体的映射。

继承 EntityController<TEntity, TModel>;未指定能力特性时默认开放全部六个操作:

using BugFree.Controllers.Core.Basis;

using Microsoft.AspNetCore.Mvc;

[Area("System")]
public sealed class UserController : EntityController<UserEntity, UserModel>
{
    public UserController(IServiceProvider serviceProvider) : base(serviceProvider) { }
}

生成的路由形如:/api/System/v1/User/Query。新增、更新和保存成功后,响应中的 data 是写入后的原模型,数据库生成的主键或默认值会复制回该模型。

3. 选择开放的实体操作

只读控制器不再需要另一套继承层次,直接声明能力:

using BugFree.Controllers.Core.Attributes;

[Area("System")]
[ExposeEntityActions(EntityActions.ReadOnly)]
public sealed class ReadOnlyUserController : EntityController<UserEntity, UserModel>
{
    public ReadOnlyUserController(IServiceProvider serviceProvider) : base(serviceProvider) { }
}

也可以任意组合,例如只开放列表查询和新增:

[Area("System")]
[ExposeEntityActions(EntityActions.Query | EntityActions.Add)]
public sealed class UserImportController : EntityController<UserEntity, UserModel>
{
    public UserImportController(IServiceProvider serviceProvider) : base(serviceProvider) { }
}
能力值 开放操作
None 不开放任何带 EntityActionAttribute 的标准操作
ReadOnly QueryGet
Editable QueryGetAddUpdateUpsert,不含 Delete
All 六个标准操作全部开放

被关闭的标准操作会从 MVC 应用模型中移除,因此不会进入路由和 API Explorer;派生控制器自行定义且未标记 EntityActionAttribute 的 Action 不受影响。

4. CRUD 行为

Action HTTP 方法 当前行为
Query POST 按筛选和分页参数查询;未指定 Sort / OrderBy 时优先按唯一键降序
Get GET 按主键获取可编辑实体;未找到时成功响应中的 datanull
Add PUT 新增实体,并把持久化后的字段复制回模型
Update PUT 更新实体,并把持久化后的字段复制回模型
Upsert PUT 唯一键为 null 时新增,否则更新;实体没有唯一键时抛出异常
Delete PUT、DELETE 根据删除字段配置执行软删除或物理删除;主键为空、实体不存在时保持幂等成功

Upsert 只判断唯一键是否为 null。空字符串、0Guid.Empty 等非 null 值都会进入更新路径。

软删除实体若使用“非主键字符串唯一键”,删除时会给原唯一键追加随机后缀,以释放原唯一值。

5. 配置控制器

using BugFree.Controllers.Core.Basis;

using Microsoft.AspNetCore.Mvc;

[Area("System")]
public sealed class AppConfigController : ConfigController<AppConfigOptions>
{
    public AppConfigController(IServiceProvider serviceProvider) : base(serviceProvider) { }
}

配置说明

IP 访问控制

在配置文件(如 appsettings.json)中:

{
  "AccessDecisionRules": {
    "Allows": {
      "Enabled": true,
      "IpRules": ["192.168.1.0/24", "10.0.0.1-10.0.0.100", "114.114.114.114"]
    },
    "Denies": {
      "Enabled": true,
      "IpRules": ["0.0.0.0/8", "10.0.0.5"]
    }
  }
}
  • IpAccessControlMiddleware 当前按 Deny → Allow → 默认放行 的顺序判断;同一 IP 同时命中两组规则时会拒绝。
  • 未命中 Allows 不会自动拒绝,因此当前 Allows 不是“必须命中的白名单”。
  • 支持:单 IP、CIDR(192.168.1.0/24)、IP 范围(10.0.0.1-10.0.0.100
  • DynamicEvaluator 可在静态规则未命中时执行程序化判断;该委托不会从 JSON 配置反序列化。

CORS 域名控制

{
  "CorsOriginRules": {
    "Enabled": true,
    "AllowedDomains": ["example.com", "*.example.com"]
  }
}

支持精确域名和 *.example.com 形式的子域名通配符。配置未启用或列表为空时允许所有来源;使用 AllowCredentials() 时应仅配置可信来源。

安全响应头

{
  "ResponseHeader": {
    "Enabled": true,
    "RemoveHeaders": ["X-AspNet-Version", "X-AspNetMvc-Version"],
    "XFrameOptions": "SAMEORIGIN",
    "StrictTransportSecurity": "max-age=31536000; includeSubDomains",
    "ContentSecurityPolicy": "default-src 'self'; script-src 'self'"
  }
}

SecurityResponseHeaderMiddleware 还支持 Referrer-Policy、COOP、CORP、可选 COEP 和安全策略报告端点。Debug 构建默认关闭,非 Debug 构建默认开启;RemoveHeaders 在响应开始前最后执行,具有最终移除优先级。


响应格式

BugFreeController 构建的成功和失败结果统一使用 Response 结构:

{
  "code": 200,
  "message": "执行成功",
  "data": {
    "id": 1,
    "name": "示例"
  },
  "runtime": null
}

下表列出 ResponseCode 可表达的状态。当前 EntityController 的六个标准操作成功时统一使用业务码 200201204 等枚举值需由自定义响应策略或业务控制器显式采用。

响应码 说明
200 成功
201 新建或修改成功
202 请求已进入后台队列
204 删除成功
400 请求失败
401 未授权
402 令牌续期
403 禁止访问
404 资源不存在
406 请求格式错误
410 资源已永久删除
500 服务器异常
502 / 503 / 504 网关或服务可用性错误

IpAccessControlMiddleware 在拒绝请求时直接返回 HTTP 403 和纯文本 Access Denied,不经过统一 Response 包装。


主要依赖

包名 说明
BugFree.Cache 多级缓存(HybridCache)
BugFree.XCode.Extensions XCode ORM 扩展
Microsoft.AspNetCore.Authentication.JwtBearer JWT 认证
Asp.Versioning.Mvc.ApiExplorer API 版本控制
Microsoft.AspNetCore.App ASP.NET Core 共享框架

项目结构

BugFree.Controllers.Core/
├── Abstractions/
│   └── Application/        ← 响应服务接口
├── Core/
│   ├── Attributes/         ← 实体能力、缓存和日志分类特性
│   ├── Basis/              ← BugFree、实体和配置控制器基类
│   ├── Middleware/         ← IP 访问控制和安全响应头中间件
│   └── Shared/             ← 默认响应服务与 MVC 元数据解析
├── Extensions/             ← 服务注册、JSON 和 HttpContext 扩展
├── Models/
│   ├── Requests/           ← 请求模型(Page)
│   └── Responses/          ← 响应模型(Response, RunTimeContext)
├── Options/                ← IP、CORS、响应头、分页和 Redis 配置
└── docs/                   ← 设计资料

许可

项目的 NuGet 包许可证声明为 MIT,见 Directory.Build.props

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.2.2026.811-beta1725 30 8/11/2026
1.2.2026.810-beta1624 44 8/10/2026
1.2.2026.810-beta1537 44 8/10/2026
1.2.2026.807-beta0945 48 8/7/2026
1.2.2026.806-beta1446 46 8/6/2026
1.2.2026.806-beta1227 48 8/6/2026
1.2.2026.806-beta1137 48 8/6/2026
1.2.2026.806-beta0938 46 8/6/2026
1.2.2026.628-beta1538 73 6/28/2026
1.2.2026.624-beta1505 71 6/24/2026
1.2.2026.623-beta1237 72 6/23/2026
1.2.2026.616-beta1005 69 6/16/2026
1.2.2026.615-beta1108 73 6/15/2026
1.2.2026.614-beta1951 64 6/14/2026
1.2.2026.613-beta1704 71 6/13/2026
1.1.2026.612-beta1017 66 6/12/2026
1.1.2026.128-beta1507 83 1/28/2026
1.1.2026.121-beta1615 81 1/21/2026
1.1.2026.121-beta1424 78 1/21/2026
1.1.2026.121-beta1413 73 1/21/2026
Loading failed

统一 API/MVC 控制器基类体系;5层实体控制器(Empty→Query→Get→ReadOnly→Entity);IP 访问控制中间件;安全响应头注入;统一响应模型;配置热更新控制器。