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

C# API控制器返回400,为何JavaScript Fetch显示422状态码?

问题原因与解决方案:C# API返回状态码与Fetch接收不一致

核心原因

你在C#代码中调用了UnprocessableEntity()方法,这个方法在ASP.NET Core中默认会将HTTP响应的状态码设置为422,哪怕你在ProblemDetails对象里指定了Status=400,也只会修改响应体JSON中的status字段,不会覆盖HTTP层面的状态码。

Fetch的response.status读取的是HTTP响应头里的状态码,而非响应体中的status字段,所以会显示422——这和Fetch的实现无关,是C#控制器的代码逻辑问题。

解决方案

要返回400 Bad Request状态码,你需要替换UnprocessableEntity()方法,改用以下两种方式之一:

方式1:使用BadRequest()方法

BadRequest()是ASP.NET Core中专门用于返回400状态码的方法,传入ProblemDetails后,会同时将HTTP状态码和响应体中的status字段设为400:

if (!string.IsNullOrEmpty(category) && category != "http://terminology.hl7.org/CodeSystem/observation-category|laboratory")
{
    return BadRequest(new ProblemDetails
    {
        Title = "Ongeldige parameter",
        Detail = "De enige toegestane waarde voor 'category' is 'http://terminology.hl7.org/CodeSystem/observation-category|laboratory'.",
        Status = 400
    });
}

方式2:手动指定状态码

如果需要更灵活地控制状态码,可以使用StatusCode()方法直接传入状态码和响应内容:

if (!string.IsNullOrEmpty(category) && category != "http://terminology.hl7.org/CodeSystem/observation-category|laboratory")
{
    var problemDetails = new ProblemDetails
    {
        Title = "Ongeldige parameter",
        Detail = "De enige toegestane waarde voor 'category' is 'http://terminology.hl7.org/CodeSystem/observation-category|laboratory'.",
        Status = 400
    };
    return StatusCode(StatusCodes.Status400BadRequest, problemDetails);
}

补充说明

  • HTTP 400:表示请求格式错误(比如参数格式不合法),对应BadRequest()方法。
  • HTTP 422:表示请求格式正确,但语义错误(比如参数值不符合业务规则),对应UnprocessableEntity()方法。
  • 响应体中的status字段是ProblemDetails对象的属性,和HTTP响应头的状态码是两个独立内容,不要混淆。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 19:52:08