繁体   English   中英

Swagger - Web API - 可选的查询参数

[英]Swagger - Web API - Optional query parameters

[HttpGet]
[Route("students")]
[SwaggerOperation(Tags = new[] { "Student" })]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(ResponseModel<IList<Student>>))]
[SwaggerResponseExample(HttpStatusCode.OK, typeof(StudentResponseExample))]
[SwaggerResponse(HttpStatusCode.InternalServerError)]
public IHttpActionResult SearchStudent()
    {
        IDictionary<string, string> searchParams = null;
        searchParams = ControllerContext.GetQueryStrings();
        .
        .
        .

    }

上面的 API 有三个可选参数,它们将作为查询字符串传递

  1. 同步日期 - 长
  2. 偏移量 - int
  3. 限制 - 整数

用户无法在 swagger UI 中输入这些可选的查询参数。 请指导我实现可选的查询参数。

我正在使用 swashbuckle 并且我更喜欢使用注释,而不是在每个 API 方法上都有冗长的评论部分来实现 swagger 功能。

我参考了以下添加查询字符串参数到我的 Swagger 规范并在 Web API 的Filters文件夹中创建了SwaggerParameterAttribute类,当尝试在 G lobalConfiguration.Configuration .EnableSwagger 中添加OperationFilter时,它抛出类型或命名空间名称SwaggerParametersAttributeHandler could not被发现。 我什至添加了Filters文件夹命名空间,但错误仍然存​​在。

请指导如何在 swagger 中实现可选的查询参数

Swagger 的工作方式是根据您的 Action 签名提取参数,即您的 Action 的参数,但在这里您从 ControllerContext 中获取这些值,显然 Swagger 永远不会意识到这些值。

所以您需要更改 Action 的签名并在那里传递您的参数。

如果您将它们设为可空类型,它们将被视为可选的 -

[HttpGet]
[Route("students")]
[SwaggerOperation(Tags = new[] { "Student" })]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(ResponseModel<IList<Student>>))]
[SwaggerResponseExample(HttpStatusCode.OK, typeof(StudentResponseExample))]
[SwaggerResponse(HttpStatusCode.InternalServerError)]
public IHttpActionResult SearchStudent(long? SyncDate = null,int? OffSet = null,int? Limit = null)
    {
        // Use the variables now here
        .
        .
        .

    }

这对我有用:

[System.Web.Http.HttpGet] 
[Route("api/DoStuff/{reqParam}")]  
[Route("api/DoStuff/{reqParam}/{optParam1:alpha?}/{optParam2:datetime?}")]
public string Get(string reqParam, string optParam1= "", string optParam2= "")

它确实在我的 Swagger UI 中创建了两个部分,但这对我有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM