Swagger-Web API-可选查询参数

Gop*_*opi 5 c# asp.net-web-api swagger swashbuckle

[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();
        .
        .
        .

    }
Run Code Online (Sandbox Code Playgroud)

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

  1. SyncDate-长
  2. 偏移-int
  3. 限制-整数

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

我正在使用swashbuckle,我更喜欢使用批注,而不是在每种API方法上都花很多篇幅来了解各种功能。

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

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

Ips*_*aur 8

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

    }
Run Code Online (Sandbox Code Playgroud)

  • 那么 System.String 是引用类型呢? (3认同)
  • 对于字符串,还应该以SearchStudent(string name = null)的形式传递,以便WebApi将其识别为可选参数 (3认同)
  • 谢谢,但是在不固定的UI中会根据需要显示。如何将其更改为可选? (2认同)
  • @TechJerk 刚刚更新了我的答案,将空值分配给参数并使它们成为可选的。 (2认同)