FastEndpoints构建REST API指南:eShopOnWeb PublicApi源码逐行解读
FastEndpoints构建REST API指南:eShopOnWeb PublicApi源码逐行解读
eShopOnWeb 是微软出品的 ASP.NET Core 示例应用,其 PublicApi 项目专门演示了如何使用 FastEndpoints 框架快速构建 REST API。本文带你逐行解读这套真实生产级源码:从启动配置、端点类写法、JWT 认证、Swagger 文档到统一异常处理,帮你快速掌握用 FastEndpoints 写 REST API 的全部关键点。
📌 什么是 PublicApi 项目?
PublicApi 位于 src/PublicApi/,官方在 README.md 中这样描述:
该文件夹演示如何将 API 端点配置为独立的类,可与 Web/Controllers/Api 中传统的 Controller 方式对比。
它的核心思想一句话就能概括:
一个类 = 一个 API 端点,配置、绑定、返回、文档全在一个文件里写完。
项目通过中央包管理文件 Directory.Packages.props 锁定 FastEndpoints 5.34.0 版本,配合 JWT Bearer 认证与 Swagger UI,构成一个完整的 REST API 工程模板。
🚀 FastEndpoints 快速上手:Program.cs 启动流程解读
打开 Program.cs,整个启动流程只有 4 步关键操作:
builder.Services.AddFastEndpoints(); // ① 注册 FastEndpoints 服务(第20行)
...
builder.Services.AddJwtAuthentication(); // ② JWT 认证
...
app.UseFastEndpoints(); // ③ 挂载所有端点(第82行)
app.Run();
其余注册逻辑都封装在扩展方法中:
| 扩展方法 | 作用 | 位置 |
|---|---|---|
AddCustomServices |
注册仓储、IUriComposer、Token 服务 |
Extensions/ServiceCollectionExtensions.cs |
AddJwtAuthentication |
配置 JWT Bearer 令牌验证 | Extensions/ServiceCollectionExtensions.cs |
AddSwagger |
配置 Swagger + Bearer 认证方案 | Extensions/ServiceCollectionExtensions.cs |
SeedDatabaseAsync |
启动时初始化数据库种子数据 | Extensions/WebApplicationExtensions.cs |
💡 要点:UseFastEndpoints() 会自动发现所有 Endpoint 子类并注册路由,无需任何手动路由配置。
🔍 端点类解剖:Configure + ExecuteAsync 两段式写法
FastEndpoints 端点继承 Endpoint<TRequest, TResponse>,固定包含两段:
Configure()—— 声明式配置:HTTP 方法 + 路由 + 权限 + Swagger 描述ExecuteAsync()—— 业务逻辑:接收强类型请求,返回强类型响应
以最简单的品牌列表端点 CatalogBrandListEndpoint.cs 为例:
public override void Configure()
{
Get("api/catalog-brands"); // GET 方法与路由
AllowAnonymous(); // 允许匿名访问
Description(d =>
d.Produces<ListCatalogBrandsResponse>() // 自动生成 Swagger 文档
.WithTags("CatalogBrandEndpoints"));
}
依赖服务(如仓储、AutoMapper.IMapper)直接通过主构造函数注入,例如 AuthenticateEndpoint.cs 注入了 SignInManager 与 ITokenClaimsService 两个服务,零样板代码。
认证端点 AuthEndpoints/AuthenticateEndpoint.cs 展示了完整的登录流程:调用 PasswordSignInAsync 验证密码,成功后通过 ITokenClaimsService 签发 JWT 并放入响应体。
🧩 请求与响应:BaseRequest / BaseResponse 与 CorrelationId
所有消息共享同一个基类 BaseMessage.cs:
protected Guid _correlationId = Guid.NewGuid();
public Guid CorrelationId() => _correlationId;
- BaseRequest.cs —— 所有请求类的基类
- BaseResponse.cs —— 响应构造时复用请求的 CorrelationId
这样一次请求的入参与出参共享同一追踪 ID,方便日志排查。响应示例见 ListPagedCatalogItemResponse.cs:
public ListPagedCatalogItemResponse(Guid correlationId) : base(correlationId) { }
💡 细节加分项:CustomSchemaFilters.cs 会在 Swagger 文档中自动移除 CorrelationId 属性——内部追踪字段不暴露给 API 消费者,这是很专业的 API 设计习惯。
🛠 完整 RESTful CRUD 端点实战
PublicApi 的目录结构按资源分文件夹组织:AuthEndpoints/、CatalogItemEndpoints/、CatalogBrandEndpoints/、CatalogTypeEndpoints/。全部端点一览:
| 方法 | 路由 | 端点类 | 说明 |
|---|---|---|---|
| GET | api/catalog-items |
CatalogItemListPagedEndpoint.cs | 分页 + 条件筛选列表 |
| GET | api/catalog-items/{id} |
CatalogItemGetByIdEndpoint.cs | 按 ID 查询 |
| POST | api/catalog-items |
CreateCatalogItemEndpoint.cs | 创建(管理员) |
| PUT | api/catalog-items |
UpdateCatalogItemEndpoint.cs | 更新(管理员) |
| DELETE | api/catalog-items/{id} |
DeleteCatalogItemEndpoint.cs | 删除(管理员) |
| POST | api/authenticate |
AuthenticateEndpoint.cs | 登录获取 Token |
分页查询:Specification 规格模式做条件筛选
CatalogItemListPagedEndpoint.cs 是全文最值得学习的端点,它展示了"筛选 + 分页 + 映射"标准套路:
- 请求类 ListPagedCatalogItemRequest.cs 用构造函数绑定查询参数(
pageSize、pageIndex、catalogBrandId、catalogTypeId),FastEndpoints 自动完成 URL 查询串 → 强类型对象的绑定; - 先用 CatalogFilterSpecification 数出总数,再用 CatalogFilterPaginatedSpecification 取当前页数据;
- 通过
AutoMapper映射为 CatalogItemDto,并用IUriComposer把图片文件名拼成完整 URL; - 用
Math.Ceiling算出PageCount返回给前端渲染分页器。
创建端点:201 状态码与 Location 头自动生成
CreateCatalogItemEndpoint.cs 展示了写操作的权限配置:
Post("api/catalog-items");
Roles(Constants.Roles.ADMINISTRATORS); // 仅管理员角色可访问
AuthSchemes(JwtBearerDefaults.AuthenticationScheme); // 指定 JWT 认证方案
业务上有两个亮点:
- 重名校验:用 CatalogItemNameSpecification 查重,冲突时抛出
DuplicateException; - 201 响应:最后调用
SendCreatedAtAsync<CatalogItemGetByIdEndpoint>(第65行),FastEndpoints 会自动返回201 Created并生成指向新资源的Location头——不用手写任何状态码逻辑。
更新与删除:TypedResults 优雅返回 404
UpdateCatalogItemEndpoint.cs 与 DeleteCatalogItemEndpoint.cs 的返回类型是联合类型 Results<Ok<Response>, NotFound>:
if (itemToDelete is null)
return TypedResults.NotFound(); // 自动返回 404
await itemRepository.DeleteAsync(itemToDelete, ct);
return TypedResults.Ok(response);
更新端点还顺带演示了领域模型思想:不直接改实体属性,而是调用实体的 UpdateDetails、UpdateBrand、UpdateType 领域方法,保持变更封装在领域层内部。
🔐 JWT 认证与 Swagger 文档配置
认证链路是这样闭环的:
- ServiceCollectionExtensions.cs 中
AddJwtAuthentication()用对称密钥(AuthorizationConstants.JWT_SECRET_KEY)配置令牌验证参数; - 客户端调用
POST api/authenticate获取 Token; - 携带
Bearer <token>请求写接口,Roles(ADMINISTRATORS)自动完成角色校验; - CORS 策略 AddCorsPolicy 只放行 appsettings.json 中配置的
webBase来源,保证 Web 前端可跨域调用 API。
文档即代码:每个端点 Description(d => ...) 中的 Produces 与 WithTags 直接生成 Swagger 文档,启动后访问 /swagger/v1/swagger.json(Program.cs 第79行)即可打开文档页,AddSecurityDefinition("Bearer", ...)(ServiceCollectionExtensions.cs 第77行)还支持在 Swagger UI 里直接粘贴 Token 调试受保护接口。
🛡 统一异常处理:ExceptionMiddleware 全局兜底
ExceptionMiddleware.cs 是挂在所有端点之外的最后防线(Program.cs 第62行 注册):
catch (Exception ex)
{
if (exception is DuplicateException) → 409 Conflict
else → 500 Internal Server Error
}
所有异常统一序列化为 ErrorDetails JSON 结构返回,保证 API 的错误响应格式一致——前端只需处理一种错误格式。
✅ 总结:FastEndpoints 的 4 个核心优势
| 优势 | 本项目对应实践 |
|---|---|
| 类式组织,端点即文件 | CatalogItemEndpoints/ 下 5 个端点 5 个类 |
| 自动参数绑定 | 构造函数式 Request 类绑定查询参数 |
| 内置 Swagger | Description(d => ...) 一段声明生成完整文档 |
| 约定式响应 | SendCreatedAtAsync / TypedResults 免写状态码 |
📚 延伸阅读:
- 端点总入口:src/PublicApi/Program.cs
- 项目说明:src/PublicApi/README.md
- 对比传统 Controller 写法:src/Web/Controllers/Api/
- 端点测试范例:tests/PublicApiIntegrationTests/
FastEndpoints 用"一个类一个端点"的极简模型,把路由、绑定、校验、文档、认证收敛到同一个文件里。读懂 eShopOnWeb 的 PublicApi,你拿到的就是一份可以直接套用的 REST API 工程模板。