Swagger - Web API - Optional query parameters

浪子不回头ぞ 提交于 2019-12-10 14:57:00

问题


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

    }

The above API has three optional parameters which will be pass as query string

  1. SyncDate - Long
  2. OffSet - int
  3. Limit - int

There is no option for user to enter these optional query parameters in swagger UI. Please guide me to implement the optional query parameters.

I am using swashbuckle and I prefer to use annotations rather than having a lengthy comment section over each API method for swagger functionalities.

I referred the following Adding Query String Params to my Swagger Specs and created the SwaggerParameterAttribute class in Filters folder of Web API and when trying to add the OperationFilter in GlobalConfiguration.Configuration .EnableSwagger as given, it throws type or the namespace name SwaggerParametersAttributeHandler could not be found. I even added the Filters folder namespace but still the error exists.

Please guide on how to implement the optional query parameters in swagger


回答1:


The way Swagger works it pulls out parameters based on your signature of Action i.e parameters to your Action, but here you are getting these value from ControllerContext which obviously Swagger will never be aware of.

So You need to change the signature of the Action and pass your parameters there.

They will be treated as optional if you make them of nullable type -

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

    }


来源:https://stackoverflow.com/questions/46764769/swagger-web-api-optional-query-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!