How to leave parameter optional, API Asp.net core

Asked

Viewed 118 times

0

I have a question on how to leave optional parameters in the method call in the API.

I have the following method:

[HttpGet("{aplicativoId}/{moduloId}/{taxaId}/{musicaId}/{produtoId}")]
[ProducesResponseType(typeof(IEnumerable<AppDto>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<IEnumerable<AppDto>>> GetAsync()
{
       
    var apps = await _testHandler.GetAsync(aplicativoId);
    return Ok(apps);
}

How do I make them all optional? In case, if I pass the 5 values, the method bring the get of the 5 values, if I pass 4 bring only until the musicaId, if pass 3 only until the taxaId and so successively, has some form ?

1 answer

0

To create an optional parameter in a route template, just place a question mark at the end of the parameter, example:

[HttpGet("{aplicativoId?}")]

However, when creating more complex routes, the optional parameters should always be the last parameters of the route, so that the ASP . NET can correctly identify your route.

In your example, since all parameters are optional, I would move everyone within your Getasync method, preserving your route independent of optional parameters:

[HttpGet]
public async Task<ActionResult<IEnumerable<AppDto>>> GetAsync(int aplicativoId, int moduloId, int taxaId, int musicaId, int produtoId)

But an int variable can never be zero, and its default value is always 0, so you can do the following check in the controller:

if (aplicativoId > 0 && moduloId > 0)
{
   var apps = await _testHandler.getAsync(aplicativoId,moduloId)
}
  • but this way when executing via Swagger will not appear the optional fields for the person pssar value or not to test the api

  • If I pass everything on Getasync they are all as optional, the first 2 are mandatory

Browser other questions tagged

You are not signed in. Login or sign up in order to post.