如何在swagger for .net core API方法中设置非强制性参数

w1jd8yoj  于 2023-10-18  发布在  .NET
关注(0)|答案(2)|浏览(188)

我注意到,我的 Swagger 的索引页面,呈现一个强制性的字段id,虽然我在代码中设置[HttpGet("{id?}")]
以下是整个方法:

/// <summary>
///  Returns all projects
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesDefaultResponseType]
[HttpGet("{id?}")]
public async Task<IActionResult> Get([FromRoute] int? id)
{
    return Ok(await Mediator.Send(new GetProjectsQuery { Id = id }));
}

我哪里做错了?

slsn1g29

slsn1g291#

这里的问题有点老了,不确定你是否找到了解决方案
但我建议您可以尝试使用路径属性
您可以参考Microsoft提供的文档
下面是未经测试的示例代码

/// <summary>
///  Returns all projects
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesDefaultResponseType]
[Route("api/Get")]
[Route("api/Get/{id}")]
[HttpGet]
public async Task<IActionResult> Get([FromRoute] int? id)
{
    return Ok(await Mediator.Send(new GetProjectsQuery { Id = id }));
}
np8igboo

np8igboo2#

试试这个。从你的HttpVerb中删除id?,从方法签名中删除FromRoute

/// <summary>
///  Returns all projects
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesDefaultResponseType]
[HttpGet]
public async Task<IActionResult> Get(int? id)
{
    return Ok(await Mediator.Send(new GetProjectsQuery { Id = id }));
}

相关问题