WebAPI2 Optional Parameters not working correctly

2k views Asked by At

I am attempting to have optional parameters for my WebAPI2 service function. Here is the definition with the route:

[HttpGet, Route("mp/CEG/{ST?}/{PR?}/{DES?}"), ResponseType(typeof(CEG))]
public object CEG(string ST = null, string PR = null, string DES = null)

However, when I document it as below and attempt to run the test in the Swagger UI (built using Swashbuckle), all parameters state that they are required and I cannot submit a test with no paramters.

XMLDoc:

/// <summary>
///     Gets list of Apps for passed ST, PR and/or DES 
/// </summary>
/// <param name="ST">ST</param>
/// <param name="PR">PR</param>
/// <param name="DES">DES</param>
/// <returns>List of CE Approvals</returns>

Any Ideas?

The function works with no parameters when running the functional test within Visual Studio.
It's just the SwaggerUI/Swashbuckle that is causing the issue. I am using that to give my consumers the chance to do tests.

update to Routes

[HttpGet, Route("mp/CEG/{ST}"),
          Route("mp/CEG/{PR}"),
          Route("mp/CEG/{DES}"),
          Route("mp/CEG/{ST}/{PR}"),
          Route("mp/CEG/{ST}/{DES}"),
          Route("mp/CEG/{PR}/{DES}"),
          ResponseType(typeof(CEG))]
1

There are 1 answers

7
venerik On BEST ANSWER

Your route is not compliant with Swagger 2.0. As the specification says about parameters (in my words):

If the parameter is in "path", the parameter is always required.

Why don't you change the parameters to query parameters like so:

[HttpGet, Route("mp/CEG"), ResponseType(typeof(CEG))]
public object CEG(string ST = null, string PR = null, string DES = null)