问题描述
我有一个在属性中定义路由的 WebAPI 方法,有一个强制参数和一个可选参数:
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)
{
我还使用 Swashbuckle/Swagger 来生成文档.问题是 Swagger 总是将我的可选参数标记为必需.
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?}")]
使这两个参数都像必需的一样,它也不会使 Swagger 将其显示为可选.
makes both parameters acting like they are required, it doesn't make Swagger to show it as optional either.
有没有办法使用 Swagger 为可选参数生成正确的文档?
Is there a way to generate correct documentation for optional parameters with Swagger?
推荐答案
如果重载方法,Swashbuckle 将生成两个不同的 Swagger 端点.一种方法有参数,另一种方法没有,并使用缺失"参数的默认值调用第一个方法.如果您使用诸如 HyprLinkr 之类的东西来生成 HATEOAS 链接,这还有一个优势,因为您不能在表达式中包含可选参数.
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);
}
希望对您有所帮助.
这篇关于带有 Swagger 文档的可选 WebAPI 路由参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!