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. SyncDate - 长
  2. OffSet - 整数
  3. 限制 - 整数

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

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

我参考了以下 并在 Web [=] 的 Filters 文件夹中创建了 SwaggerParameterAttribute class 44=] 并且尝试在 GlobalConfiguration.Configuration 中添加 OperationFilter 时 .EnableSwagger 作为给定的,它抛出类型或命名空间名称 SwaggerParametersAttributeHandler 找不到。我什至添加了 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 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 但这对我有用。