Swagger文档中的可选WebAPI路由参数 [英] Optional WebAPI routing parameters with Swagger documentation

查看:497
本文介绍了Swagger文档中的可选WebAPI路由参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在属性中定义路由的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.

有没有一种方法可以生成正确的

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

推荐答案

如果重载方法,Swashbuckle将生成两个不同的Swagger端点。一个方法具有参数,另一个没有参数,并使用 missing参数的默认值调用第一个方法。如果您使用类似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路由参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆