Swagger - Web API - 可选查询参数

问题描述 投票:0回答:3
[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 方法上使用冗长的注释部分来实现 swagger 功能。

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

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

c# asp.net-web-api swagger swashbuckle optional-parameters
3个回答
22
投票

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

因此您需要更改操作的签名并将参数传递到那里。

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

[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
    .
    .
    .

}

3
投票

这对我有用:

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


0
投票

试试这个:

[HttpGet("api/DoStuff/{reqParam}")]
public async Task<IActionResult> Get(string reqParam, string optParam1= "", string optParam2= "")
© www.soinside.com 2019 - 2024. All rights reserved.