Swashbuckle Swagger UI:如何从 xml 注释中的参数中删除必需的 [英] Swashbuckle Swagger UI: How to remove required from parameters in xml commenting

查看:45
本文介绍了Swashbuckle Swagger UI:如何从 xml 注释中的参数中删除必需的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改控制器中某些参数的必需属性.我使用 XML 注释来链接到 Swagger.

I would like to change the required attribute on a some of the parameters in my controllers. I used XML comments in order to link to Swagger.

推荐答案

在继续之前,请仔细考虑您的参数.该参数是否真的需要,您的输入是否反映了这一点?是否有一个合理的默认值,在这种情况下预期的行为是什么?根据您的回答,您可能更喜欢以下两种解决方案之一:

Before proceeding, think carefully about your parameter. Is the parameter truly required, and does your typing reflect that? Is there a sane default value, and what would be the expected behavior in that case? Depending on your answer, you may prefer one of these two solutions:

如果 accessTokenID 具有合理的默认值,您可以在 API 签名上指定该值,Swashbuckle 将根据需要停止识别该参数.

If accessTokenID has a sane default value, you can specify that on the API signature and Swashbuckle will stop identifying the parameter as required.

例如,本例中的 id 将在 Swagger UI 中解析为可选:

For example, id in this example would resolve as optional in Swagger UI:

public HttpResponseMessage Get(int id = 0)

如果您的参数确实不是必需的,则可空类型可能更有意义(例如,如果您列出空输入的所有值):

If your parameter is truly not required, a nullable type might make more sense (for example, if you list all values on null input):

public HttpResponseMessage Get(int? id = null)

选项 2:SwaggerDefaultValue 属性

Swashbuckle GitHub 中的 解决方案创建了一个 IOperationFilter 来处理 SwaggerDefaultValue属性并将它们应用到 Swagger UI.如果您希望需要参数,但希望在 Swagger UI 中设置一些默认值,则可以使用此解决方案.

Option 2: SwaggerDefaultValue Attribute

A solution in the Swashbuckle GitHub created an IOperationFilter to process SwaggerDefaultValue attributes and apply them to Swagger UI. You can use this solution if you would prefer to require the parameter, but would like to set some default in Swagger UI.

例如,这将在 Swagger UI 文本字段中显示0"而不是(required)":

For example, this would show "0" in the Swagger UI text field instead of "(required)":

[SwaggerDefaultValue("id", "0")]
public HttpResponseMessage Get(int id)

这篇关于Swashbuckle Swagger UI:如何从 xml 注释中的参数中删除必需的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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