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

如何为Web API函数参数设置默认值?解决可选参数必填校验报错

ASP.NET Core中HttpGet参数设为可选的解决方法

你遇到的问题是ASP.NET Core模型绑定规则导致的——即便给参数设置了默认值,框架仍会将其判定为必填项。以下是两种可行的解决办法:

方法1:显式添加[FromQuery]特性

给参数加上[FromQuery]特性,明确指定该参数来自查询字符串,框架就能正确识别其可选性:

[HttpGet("ExerciseListWithHash")]
public object GetExerciseListWithHash([FromQuery] string hashString = "")
{
    return DL.GetExerciseListWithHash(hashString);
}

方法2:结合可空引用类型(.NET Core 3.0+)

如果你的项目启用了可空引用类型(项目文件中配置了<Nullable>enable</Nullable>),需要将参数声明为可空类型string?,配合默认值使用:

[HttpGet("ExerciseListWithHash")]
public object GetExerciseListWithHash([FromQuery] string? hashString = "")
{
    return DL.GetExerciseListWithHash(hashString ?? "");
}

问题原因说明

当未指定绑定源(如[FromQuery])且启用可空引用类型时,ASP.NET Core会把非可空的string参数默认标记为必填项,即便设置了默认值也会被忽略。通过显式指定绑定源或声明可空类型,就能让框架正确识别参数的可选性。


你的原始控制器代码:

[HttpGet("ExerciseListWithHash")]
public object GetExerciseListWithHash(string hashString = "")
{
    return DL.GetExerciseListWithHash(hashString);
}

调用时返回的400错误信息:

Error: response status is 400

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-374015b9a04f6f82b0eb4d564ac89807-bdae114f0a4577c8-00",
  "errors": {
    "hashString": [
      "The hashString field is required."
    ]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 19:09:28