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

ASP.NET Core如何配置可选参数并在Swagger中正确展示?

解决方案

问题根源

你使用的位置式记录定义会生成无默认值的构造函数,即使firstName和lastName是可空类型,System.Text.Json反序列化时仍会要求必须提供所有构造函数参数,缺失则直接抛出错误,导致请求无法进入控制器;同时Swagger无法识别这些参数的可选性,因为没有默认值或显式标记。

步骤1:修改Person记录定义

给可选参数添加默认值= null,并确保[Required]标记应用到属性而非构造函数参数:

public record Person(
    [property: Required] string Email,
    string? FirstName = null,
    string? LastName = null);

这样会生成带可选参数的构造函数,反序列化器在缺失属性时会自动使用默认值(null),同时模型验证和Swagger能正确识别Email为必填项,其余为可选。

步骤2:优化Swagger显示(可选)

如果Swagger仍未正确标记可选参数,可安装Swashbuckle.AspNetCore.Annotations包,显式添加Swagger schema标记:

using Swashbuckle.AspNetCore.Annotations;

public record Person(
    [property: Required]
    [property: SwaggerSchema(Required = true)]
    string Email,

    [property: SwaggerSchema(Nullable = true, Required = false)]
    string? FirstName = null,

    [property: SwaggerSchema(Nullable = true, Required = false)]
    string? LastName = null);

步骤3:调整控制器配置

将[Controller]改为[ApiController],它会自动处理模型验证错误并返回标准化400响应,同时增强模型绑定的兼容性:

[ApiController]
[Route("api/[controller]")]
public class ApiController : ControllerBase
{
    [HttpPost]
    public bool CheckPerson([FromBody] Person blah)
    {
        // 业务逻辑
    }
}

验证

修改后,发送{ "email": "a@b.com" }这类缺失可选参数的请求时,请求会正常进入控制器,blah.FirstName和blah.LastName会被设为null;同时Swagger文档中会清晰标记Email为必填,其余参数为可选。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:11:12