【问题标题】:Swagger - Web API - Optional query parametersSwagger - Web API - 可选查询参数
【发布时间】:2018-03-27 15:32:10
【问题描述】:
[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. SyncDate - 长
  2. OffSet - int
  3. 限制 - 整数

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

我正在使用 swashbuckle,我更喜欢使用注释,而不是在每个 API 方法上使用冗长的注释部分来实现大摇大摆的功能。

我参考了以下Adding Query String Params to my Swagger Specs 并在 Web API 的 Filters 文件夹中创建了 SwaggerParameterAttribute 类,并尝试在其中添加 OperationFilter GlobalConfiguration.Configuration .EnableSwagger 作为给定,它抛出类型或命名空间名称 SwaggerParametersAttributeHandler 找不到。我什至添加了 Filters 文件夹命名空间,但错误仍然存​​在。

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

【问题讨论】:

    标签: c# asp.net-web-api swagger swashbuckle


    【解决方案1】:

    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 here
        .
        .
        .
    
    }
    

    【讨论】:

    • 谢谢,但在 swagger UI 中,它会根据需要显示。如何将其更改为可选?
    • @TechJerk 刚刚更新了我的答案,将空值分配给参数并使它们成为可选。
    • 引用类型的 System.String 呢?
    • @Grigory 字符串将作为 null 传入,您无需执行任何特殊操作。
    • 对于字符串,你也应该作为SearchStudent(string name = null) 传递,以便WebApi 将其识别为可选参数
    【解决方案2】:

    这对我有用:

    [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 中创建了两个部分,但这对我有用。

    【讨论】:

    • 这并不能解决问题。在 swagger 中,可选参数仍按要求显示。
    猜你喜欢
    • 1970-01-01
    • 2015-12-28
    • 2012-08-05
    • 2020-01-06
    • 1970-01-01
    • 2017-07-14
    • 2016-11-09
    • 2013-04-10
    • 1970-01-01
    相关资源
    最近更新 更多