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

设置默认值的HttpGet接口参数仍被判定为必填项报错400

ASP.NET Core HttpGet接口参数设为可选仍报400错误的解决办法

我原本想用以下代码把接口参数设为可选:

[HttpGet]
public IEnumerable<Foobar> GetFoobar(
    string DateRange = null,
    string Version = null)
{
    return service.GetAll(DateRange, Version);
}

但调用该API时却返回400错误,错误信息如下:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-4d3cb9173485547bfb36cb2a723725c2-f39d9a1bd4fad052-00",
  "errors": {
    "DateRange": [
      "The DateRange field is required."
    ],
    "Version": [
      "The Version field is required."
    ]
  }
}

问题原因

这问题大概率是**可空引用类型(Nullable Reference Types)**导致的。如果你的项目是.NET Core 3.0及以上版本,默认启用了可空引用类型特性,string会被默认视为非空引用类型——哪怕你给它设置了= null的默认值,模型验证依然会将其判定为必填项,因为编译器层面认为string不能为null,进而触发验证错误。

另外,未明确指定参数绑定源也可能引发这个问题:ASP.NET Core绑定查询字符串参数时,若未标记[FromQuery],偶尔会因绑定规则偏差,将参数误判为必填。

解决方案

  • 方案1:标记可空类型+显式指定绑定源(推荐)
    将参数改为string?(可空字符串),同时添加[FromQuery]特性明确从查询字符串获取参数,模型验证就能正确识别它们为可选参数:

    [HttpGet]
    public IEnumerable<Foobar> GetFoobar(
        [FromQuery] string? DateRange = null,
        [FromQuery] string? Version = null)
    {
        return service.GetAll(DateRange, Version);
    }
    
  • 方案2:禁用可空引用类型(不推荐)
    若不需要可空引用类型的空安全检查,可以在项目文件(.csproj)中修改配置:

    <PropertyGroup>
      <Nullable>disable</Nullable>
    </PropertyGroup>
    

    这种方式能快速解决问题,但会失去可空引用类型带来的代码安全保障,不建议在新项目中使用。

  • 方案3:使用[Optional]特性
    给参数添加[Optional]特性,明确告知模型验证该参数为可选,配合默认值使用即可:

    [HttpGet]
    public IEnumerable<Foobar> GetFoobar(
        [FromQuery, Optional] string DateRange = null,
        [FromQuery, Optional] string Version = null)
    {
        return service.GetAll(DateRange, Version);
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:31:21