Optional WebAPI routing parameters with Swagger documentation

旧街凉风 提交于 2019-12-07 23:45:18

问题


I have a WebAPI method with routing defined in an attribute, having one mandatory parameter and one optional:

    [HttpGet]
    [Route("api/ChargeCard/{cif}/{feeScheme=null}")]
    [ResponseType(typeof(ChargeCardRoot))]
    public IHttpActionResult Get(string cif, string feeScheme, ChargeCardRequestMode mode = ChargeCardRequestMode.Basic)
    {

I also use Swashbuckle / Swagger to generate documentation. The problem is that Swagger always marks my optional parameter as required.

Changing optional parameter notation to:

    [Route("api/ChargeCard/{cif}/{feeScheme?}")]

makes both parameters acting like they are required, it doesn't make Swagger to show it as optional either.

Is there a way to generate correct documentation for optional parameters with Swagger?


回答1:


If you overload your methods, Swashbuckle will generate two different Swagger endpoints. One method has the parameter, the other does not and calls the first one with the default value for the "missing" parameter. This also has the advantage of making it easier if you using something like HyprLinkr to generate HATEOAS links, as you can't have optional parameters in an expression.

[HttpGet]
[Route("api/ChargeCard/{cif}/{feeScheme}")]
[ResponseType(typeof(ChargeCardRoot))]
public IHttpActionResult Get(string cif, string feeScheme, ChargeCardRequestMode mode = ChargeCardRequestMode.Basic)
{
    // working code
}

[HttpGet]
[Route("api/ChargeCard/{cif}")]
[ResponseType(typeof(ChargeCardRoot))]
public IHttpActionResult Get(string cif, string feeScheme)
{
    return Get(cif, feeScheme, ChargeRequestMode.Basic);
}

Hope that helps.



来源:https://stackoverflow.com/questions/42512923/optional-webapi-routing-parameters-with-swagger-documentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!