-1

I noticed, that my swagger index page, renders a mandatory field id although I set in the code [HttpGet("{id?}")]

Here is the whole method:

/// <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 }));
}

Where I went wrong?

Stefan0309
  • 1,602
  • 5
  • 23
  • 61
  • Because it is in route. I think you can not nullable values in route. – sa-es-ir Apr 23 '21 at 22:19
  • But I read that it can with this question mark symbol? – Stefan0309 Apr 23 '21 at 22:24
  • How are you configuring Swagger? Do you have a screenshot of the generated spec for this method? – Connor Low Apr 23 '21 at 22:44
  • Maybe this help: https://stackoverflow.com/questions/35011192/how-to-define-an-optional-parameter-in-path-using-swagger – sa-es-ir Apr 23 '21 at 22:45
  • You might just need to give the `id` parameter a default value (i.e. `int? id = null`). [If a route parameter is optional, you must define a default value for the method parameter.](https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#optional-uri-parameters-and-default-values) – devNull Apr 23 '21 at 23:22
  • I added nullable param but still nothing..it forces me to add id – Stefan0309 Apr 24 '21 at 15:27

1 Answers1

-1

Try this. Remove the id? from your HttpVerb and the FromRoute from method signature.

/// <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 }));
}
IvanJazz
  • 763
  • 1
  • 7
  • 19
  • this is not a question how to do on another way. I know for that solution, but I want to have nullable param from route. thanks – Stefan0309 Apr 24 '21 at 15:11