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

C#返回BadRequest时自定义消息丢失,如何正确返回?

解决自定义错误信息被覆盖的问题

你的问题出在ASP.NET Core处理HttpResponseMessage的逻辑上——直接返回BadRequest(response)时,框架会自动转换响应内容,不会保留你手动设置的ReasonPhrase。以下是两种可行的解决方案:

方案一:用响应体传递自定义错误信息(推荐)

这是ASP.NET Core官方推荐的错误信息传递方式,把错误内容放在响应体中,而非依赖ReasonPhrase(HTTP规范中ReasonPhrase仅用于简短状态描述,不适合承载详细错误):

控制器代码修改

catch (Exception ex)
{
    _logger.LogError(ex, "Error amending in viewbooking");
    // 返回包含自定义消息的匿名对象
    return BadRequest(new { Message = ex.Message });
}

Blazor组件读取错误信息

response = await Http.PutAsJsonAsync("api/ViewBooking", newBooking);
if (!response.IsSuccessStatusCode)
{
    // 读取响应体中的错误数据
    var errorData = await response.Content.ReadFromJsonAsync<dynamic>();
    StringBuilder sb = new StringBuilder();
    sb.Append("Could not save - please try again or contact your administrator.");
    // 提取自定义消息,添加默认值兜底
    sb.AppendLine(errorData?.Message ?? "Unknown error occurred.");
}

方案二:手动设置ReasonPhrase(仅兼容场景使用)

如果一定要保留ReasonPhrase的传递方式,可以直接操作HttpContext来设置响应状态和描述:

控制器代码修改

catch (Exception ex)
{
    _logger.LogError(ex, "Error amending in viewbooking");
    // 设置响应状态码
    HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
    // 手动注入自定义ReasonPhrase
    HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = ex.Message;
    // 返回纯状态码结果
    return new StatusCodeResult((int)System.Net.HttpStatusCode.BadRequest);
}

Blazor组件读取

不需要修改原有的ReasonPhrase读取代码,即可获取到自定义的错误文本。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:52:42