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

2.7k views Asked by At

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

There are 1 answers

1
Dhiraj Gupta On

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.