How to mark api parameter as optional for Swagger UI for Web API 2?

℡╲_俬逩灬. 提交于 2021-01-29 03:30:29

问题


I am using Swagger for WebApi 5.5.3 nuget package for API documentation. In swagger UI it is showing required option for optional parameter.

I tried XML comment option in Visual studio. Below is the API method that i want to document:

    /// <summary>
    /// Gets the history.
    /// </summary>
    /// <param name="currentPageIndex">Index of the current page.</param>
    /// <param name="pageSize">Size of the page.</param>
    /// <param name="lastSyncDate">The last synchronize date.</param>
    /// <returns></returns>
    [HttpGet]
    [Route("GetHistory/{currentPageIndex}/{pageSize}")]
    public IHttpActionResult GetHistory(int currentPageIndex, int pageSize, DateTime? lastSyncDate)
    {
        var response = _myRepo.GetData();
        if (response == null)
            return BadRequest(Messages.InvalidPageIndex);

        return Ok(response);
    }

It is showing lastSyncDate as query parameter but it is required while I have marked it as nullable parameter.

I have also tried making currentPageIndex as nullable in xml as well as route but still all the properties as showing as required. Please help.


回答1:


Solution for this problem given below

Create Model class

    using System;
    using System.ComponentModel.DataAnnotations;

    public class SearchHistory
    {
      [Required]
      public int CurrentPageIndex { get; set; }
      [Required]
      public int PageSize { get; set; }
      public DateTime? LastSyncDate { get; set; }
    }

Change your input parameter with newly create model

 [HttpGet]
 public IHttpActionResult GetHistory(SearchHistory modle)
{
    var response = _myRepo.GetData();
    if (response == null)
        return BadRequest(Messages.InvalidPageIndex);

    return Ok(response);
}

Hope this will solve your issue.



来源:https://stackoverflow.com/questions/41342079/how-to-mark-api-parameter-as-optional-for-swagger-ui-for-web-api-2

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