如何将 api 参数标记为 Swagger UI for Web API 2 的可选参数? [英] How to mark api parameter as optional for Swagger UI for Web API 2?

查看:27
本文介绍了如何将 api 参数标记为 Swagger UI for Web API 2 的可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Swagger for WebApi 5.5.3 nuget 包来编写 API 文档.在 swagger UI 中,它显示了可选参数的必需选项.

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.

我在 Visual Studio 中尝试了 XML 注释选项.以下是我要记录的 API 方法:

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);
    }

它显示 lastSyncDate 作为查询参数,但在我将其标记为可空参数时它是必需的.

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

我还尝试使 currentPageIndex 在 xml 和路由中可以为空,但仍然按要求显示所有属性.请帮忙.

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.

推荐答案

下面给出这个问题的解决方案

Solution for this problem given below

创建模型类

    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.

这篇关于如何将 api 参数标记为 Swagger UI for Web API 2 的可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆