【问题标题】:How can I hide response code 200 with Swashbuckle.AspNetCore?如何使用 Swashbuckle.AspNetCore 隐藏响应代码 200?
【发布时间】:2019-03-24 03:59:36
【问题描述】:

喏,

我正在开发一个 asp.net web api 核心(目标框架 .NET Core 2.1)。我正在使用 Swagger 规范记录我的 API。我选择使用 Swashbuckle.AspNetCore 库。

我有一个简单的创建操作,如下所示:

    /// <summary>
    /// My summary
    /// </summary>
    /// <remarks>My remarks</remarks>
    /// <param name="value">value</param>
    /// <response code="201">Created</response>
    /// <response code="400">Data not valid</response>
    /// <response code="500">Internal Server Error</response>
    [HttpPost]
    public IActionResult Post([FromBody, BindRequired] EntityDto value)
    {
       ...
    }

问题是我生成的 swagger.json 自动创建了“200 响应”。但是因为我的操作只创建实体,所以它只返回 201 响应。这是以下 json 片段:

{
  ...
  "responses": {
    "200": {
      "description": "Success"
    },
    "201": {
      "description": "Created"
    },
    "400": {
      "description": "Data not valid"
    },
    "500": {
      "description": "Internal Server Error"
    }
  }
  ...
}

在网上冲浪我找到了 SwaggerResponseRemoveDefaults 属性,但似乎它仅在完整框架项目中受支持。

如何删除 200 响应?

【问题讨论】:

    标签: c# json asp.net-core .net-core swashbuckle


    【解决方案1】:

    为了不将默认响应代码包含在 swagger 中,您可以声明可能的返回代码

        /// <summary>
        /// My summary
        /// </summary>
        /// <remarks>My remarks</remarks>
        /// <param name="value">value</param>
        /// <returns>A newly created TodoItem</returns>
        /// <response code="201">Created</response>
        /// <response code="400">Data not valid</response>
        /// <response code="500">Internal Server Error</response>
        [HttpPost]
        [ProducesResponseType(201)]
        [ProducesResponseType(400)]
        [ProducesResponseType(500)]
        public void Post([FromBody] string value)
        {
        }
    

    【讨论】:

    • 这似乎对我不起作用。无论我在端点上使用什么 ProducesResponseType 属性,我总是会得到一组默认的响应代码
    • @MylesJ。你需要在控制器方法中添加[ProducesResponseType(201)] [ProducesResponseType(400)] [ProducesResponseType(500)],你试过了吗?
    猜你喜欢
    • 1970-01-01
    • 2018-05-16
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多