You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AutoWrapper时响应重复包装且自定义消息失效的问题

问题:AutoWrapper 响应重复包装且自定义消息失效

当前配置与代码

Program.cs 配置

var app = builder.Build();
//app.UseMiddleware<MyMiddleware>();
app.UseCors(MyAllowSpecificOrigins);
// Configure the HTTP request pipeline.
//app.UseApiResponseAndExceptionWrapper<MapResponseObject>();
app.UseApiResponseAndExceptionWrapper();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.Run();

控制器代码

[HttpGet]
[Route("GetLast12MonthBalances")]
public async Task<ApiResponse> GetLast12MonthBalances()
{
    try
    {
        return new ApiResponse("My Custom Message.",await _transactionService.GetLast12MonthBalances(null));
    }
    catch (Exception ex)
    {
        throw new ApiException(ex);
    }
}

期望与实际结果

期望响应格式

{
 "version": "1.0.0.0",
"statusCode": 200,
"message": "My Custom Message.",
"isError": null,
"responseException": null,
"result": { //my object
}

实际返回响应

{
 "message": "GET Request successful.",
 "result": {
 "version": "1.0.0.0",
 "statusCode": 200,
 "message": "My Custom Message.",
 "isError": null,
 "responseException": null,
 "result": { // my object
}

问题原因与解决方法

原因

你同时执行了两个冲突的操作:控制器手动返回ApiResponse对象,又启用了AutoWrapper的全局自动包装功能。AutoWrapper默认会对所有Action的返回值进行包装,包括你手动构建的ApiResponse,因此出现双重包装,外层的默认消息是AutoWrapper自动生成的,覆盖了你自定义的消息。

解决方法

有两种可选方案:

方案1:保留手动返回ApiResponse,关闭AutoWrapper的自动包装

修改Program.cs中的AutoWrapper配置,添加IsApiResponseExcluded = true,让AutoWrapper跳过对ApiResponse类型的包装:

app.UseApiResponseAndExceptionWrapper(options =>
{
    options.IsApiResponseExcluded = true;
});

配置后,AutoWrapper仅处理异常,不会包装你手动返回的ApiResponse,自定义消息正常生效,响应格式与期望一致。

方案2:让AutoWrapper自动处理包装,控制器直接返回业务对象

移除控制器中手动构建ApiResponse的逻辑,直接返回业务对象,同时通过AutoWrapper特性或全局配置设置自定义消息:

[HttpGet]
[Route("GetLast12MonthBalances")]
[ApiResponse(Message = "My Custom Message.")] // 设置自定义消息
public async Task<YourBusinessObjectType> GetLast12MonthBalances()
{
    try
    {
        return await _transactionService.GetLast12MonthBalances(null);
    }
    catch (Exception ex)
    {
        throw new ApiException("My Custom Message.", ex);
    }
}

还可在全局配置中设置版本号:

app.UseApiResponseAndExceptionWrapper(options =>
{
    options.Version = "1.0.0.0";
});

这样AutoWrapper会自动生成符合期望格式的响应,无需手动构建ApiResponse。

内容的提问来源于stack exchange,提问作者Raas Masood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 21:37:50