【问题标题】:Swashbuckle - swagger documentation of returned response?Swashbuckle - 返回响应的招摇文档?
【发布时间】:2017-12-24 05:54:53
【问题描述】:

Swashbuckle 不会生成带有“UserCreateResponse”输出的 swagger.json,你如何解决这个问题?

    [HttpPost]
    public async Task<IActionResult> Update([FromBody]UserCreate Request)
    {
        UserCreateResponse response = new UserCreateResponse();

        //do something here

        // returns UserCreateResponse with http status code 200
        return Ok(response);
    }

你不能这样做,因为它不会返回 http 状态码,200,400,401 等

    [HttpPost]
    public async Task<UserCreateResponse> Update([FromBody]UserCreate Request)
    {
        UserCreateResponse response = new UserCreateResponse();

        //do something here

        // returns UserCreateResponse
        return response;
    }

【问题讨论】:

    标签: c# rest asp.net-core swagger swashbuckle


    【解决方案1】:

    您可以使用以下属性指定响应类型:

    [ProducesResponseType(typeof(UserCreateResponse), 200)]
    

    【讨论】:

      【解决方案2】:

      以下解决方案仅适用于 V6.0 之前的 Swashbuckle 版本!

      从 V6.0 开始,不再支持 SwaggerResponse,请参阅 here


      另一个变体是使用SwaggerResponse 属性,它还允许提供额外的描述:

      [SwaggerResponse(HttpStatusCode.OK, "UserDTO", typeof(UserDTO))]
      public async Task<IHttpActionResult> Get([FromODataUri] int key)
      {
          var result = await UserRepo.GetAsync(key);
          ...
          return Ok(result);
      }
      

      产生如下所示的输出:

      也可以省略类型来记录不返回实体的其他状态代码:

      [SwaggerResponse(HttpStatusCode.NotFound, "no data found")]
      [SwaggerResponse(HttpStatusCode.BadRequest, "requiered request headers not found")]
      

      【讨论】:

      • 不幸的是,SwaggerResponse 在 Swashbuckle.AspNetCore 的更新版本中已被删除。 ProducesResponseType 是要走的路,如果您仍然想要字符串解释,可以使用可选的 XML cmets(阅读更多关于 here 的信息)。
      • 感谢@JimAho 提供的信息,我不知道。我已经更新了我的答案,让读者知道。
      • 我只是简单地解决了状态码 200 到 400,同时将返回类型从 return Ok(json_structure);返回新的 JsonResult(json_structure);在异常处理程序中,问题得到了很好的解决! .
      【解决方案3】:

      从 .NET Core 2.1 开始,使用 ActionResult<T> 将是指定返回类型的推荐方法。它被 Swashbuckle 选中,并在编译时添加了类型检查。

      您还可以通过 XML 注释 (docs) 在响应中添加描述。

      所以对于 OP 的例子,它会是

      /// <summary> 
      ///     Update the user 
      /// </summary>
      /// <response code="200"> User's data </response>
      [HttpPost]
      [ProducesResponseType(StatusCodes.Status200OK)]
      public async Task<ActionResult<UserCreateResponse>> Update(...) 
      {
         ...
      }
      

      【讨论】:

        猜你喜欢
        • 2019-06-14
        • 2017-12-19
        • 2017-01-27
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-05
        相关资源
        最近更新 更多