AutoWrapper 是一个专为 ASP.NET Core API 设计的开源中间件,它能自动为你的 API 响应提供统一的格式包装,并内置了全局异常处理功能,让你能更专注于业务逻辑开发。
下面这个表格总结了 AutoWrapper 的典型响应结构,你可以快速了解它为你包装了哪些信息:
| 响应类型 | 默认格式 (关键字段) | 说明 |
|---|---|---|
| 成功 | message (字符串), isError (布尔值, 通常为false), result (对象或数组) |
成功响应体,核心数据在 result 字段。 |
| 错误 | isError (布尔值, 为true), responseException (对象) |
错误响应体,异常详情在 responseException 字段。 |
🛠️ 安装与基本配置
-
安装 NuGet 包
在你的项目目录下,使用dotnet add package AutoWrapper.Core命令来安装 AutoWrapper 包。 -
配置中间件
在Startup.cs文件的Configure方法中,在UseRouting()之后、UseEndpoints()之前添加 AutoWrapper 中间件:public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ... 其他配置 app.UseRouting(); // 添加 AutoWrapper 中间件 app.UseApiResponseAndExceptionWrapper(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
完成以上步骤后,你的 API 响应就会被自动包装了。例如,一个返回列表的 GET 请求,其原始数据可能是一个数组,但经过 AutoWrapper 包装后,返回给客户端的格式将是:
{
"message": "Request successful.",
"isError": false,
"result": [
{
"id": 1,
"name": "Item 1"
},
{
"id": 2,
"name": "Item 2"
}
]
}
🔧 自定义响应格式
如果默认的响应格式不符合你的要求,你可以通过自定义映射类和配置选项来修改。
1. 自定义属性映射
你可以创建一个类,使用 [AutoWrapperPropertyMap] 特性来映射到你喜欢的属性名。
public class CustomResponseDTO
{
[AutoWrapperPropertyMap(Prop.Message)]
public string? CustomMessage { get; set; }
[AutoWrapperPropertyMap(Prop.Result)]
public object? Data { get; set; }
[AutoWrapperPropertyMap(Prop.ResponseException)]
public object? Error { get; set; }
}
然后,在中间件中注册这个自定义类:
app.UseApiResponseAndExceptionWrapper<CustomResponseDTO>();
这样,之前的成功响应格式就会变成:
{
"customMessage": "Request successful.",
"isError": false,
"data": [
// ... 数据内容
]
}
2. 配置 AutoWrapper 选项
AutoWrapperOptions 对象允许你进行更细致的配置:
app.UseApiResponseAndExceptionWrapper(new AutoWrapperOptions
{
ShowStatusCode = true, // 在响应中显示HTTP状态码
ApiVersion = "1.0.0", // 设置API版本
IsDebug = true, // 在开发环境中开启,以在错误响应中显示堆栈跟踪等详细信息
ShowIsErrorFlagForSuccessfulResponse = true // 即使成功也包含 isError 字段
});
🚨 异常处理
AutoWrapper 会自动捕获控制器中未处理的异常,并生成统一的错误响应。
-
默认错误格式:
{ "isError": true, "responseException": { "exceptionMessage": "Unhandled Exception occurred. Unable to process the request." } }当
IsDebug设置为true时,responseException对象会包含更详细的错误信息,例如堆栈跟踪(StackTrace)。 -
抛出自定义异常:
你可以使用ApiException抛出结构更清晰的异常信息:throw new ApiException("Custom error message here.", 400, "CUSTOM_ERROR_CODE", "https://example.com/help/error-code");这会产生类似如下的错误响应:
{ "isError": true, "responseException": { "exceptionMessage": "Custom error message here.", "referenceErrorCode": "CUSTOM_ERROR_CODE", "referenceDocumentLink": "https://example.com/help/error-code" } }
💎 实用提示
- 中间件位置很重要:务必确保
UseApiResponseAndExceptionWrapper放在UseRouting之后,UseEndpoints之前,否则可能无法正常工作。 - 善用调试模式:在开发环境(
env.IsDevelopment())中,可以将IsDebug设置为true,以便获取更详细的错误信息。在生产环境中,则应将其设置为false。 - 结合其他工具:AutoWrapper 可以很好地与 Swagger(用于 API 文档)、Serilog(用于日志记录)和 FluentValidation(用于模型验证)等工具协同工作。
希望这份指南能帮助你快速上手 AutoWrapper,从而构建出更具一致性和可维护性的 ASP.NET Core API。