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

.NET 7 Minimal API中BadRequest无法返回响应体问题排查

问题:.NET 7 Minimal API中BadRequest无法返回ErrorModel响应体

我在.NET 7环境下编写了如下Minimal API接口:

app.MapPost($"{root}/v1/AuthenticateUser"
    , async Task<Results<Ok<GetTokenForResponse>, BadRequest<ErrorModel>>> 
    (HttpContext httpContext, IMediator mediator, AuthenticateBody body) =>
{
    var response = await mediator.Send(new AuthenticateUserHandler.Request(httpContext, body.UserName, body.Password));
    if (response.IsSuccessful)
        return TypedResults.Ok(response.Result);
    return TypedResults.BadRequest(response.Error);
})
.WithTags(root);

接口中Ok分支可正常返回GetTokenForResponse类型的响应体,但BadRequest分支无法返回ErrorModel类型的响应体。查阅官方文档确认BadRequest方法应支持返回指定对象,却始终找不到问题原因。相关的BaseResponse定义如下:

public record BaseResponse<T>
{
    public HttpContext? HttpContext { get; set; }
    public bool IsSuccessful => Error is null && Result is not null;
    public ErrorModel? Error { get; set; }
    public T? Result { get; set; }
}

解决方案

最终排查发现问题并非出在BadRequest方法本身,而是ErrorModel记录缺少公共getter,为其添加公共getter后问题解决。

内容的提问来源于stack exchange,提问作者Keith Barrows

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 01:13:24