使用Swagger的特定状态代码的响应模型

Kal*_*din 17 c# rest asp.net-web-api swagger

我使用Swagger来记录我的REST API(使用asp.net web api 2).对于给定的api调用,是否有一种方法可以为每个可能的响应提供响应模型?我正在使用xml注释来注释状态代码响应,如下所示:

    /// <summary>
    /// Save a person
    /// </summary>
    /// <response code="200">Ok</response>
    /// <response code="400">Bad Request</response>
    /// <response code="500">Internal Server error</response>
    public HttpResponseMessage SavePerson() {...}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

小智 34

您可以尝试在XML评论中使用cref ="TYPE HERE".

/// <response code="400" cref="CustomErrorModel">Bad Request</response>
Run Code Online (Sandbox Code Playgroud)

我会建议使用Swagger给你的注释.

[SwaggerResponse(HttpStatusCode.OK, Type = typeof(OnlineMerchantQueryResponseInformation))]
Run Code Online (Sandbox Code Playgroud)

使用此属性控制您的控制器.

  • 如果你可以从你发现这个文档的地方分享它会很好吗? (12认同)

Elt*_*ton 12

您的签名表示您正在返回HttpResponseMessage,而不是数据模型.如果您要返回IActionResult,则可以使用"ProducesResponseType"属性.

[ProducesResponseType(typeof(IEnumerable<YourModel>), 200)]
Run Code Online (Sandbox Code Playgroud)

ProducesResponsesType位于Microsoft.AspNetCore.Mvc命名空间中.

请参阅 https://github.com/domaindrivendev/Swashbuckle.AspNetCore#list-operation-responses "明确的回应"

  • 这只在Core中有效. (6认同)

小智 7

如果您使用的是 Swashbuckle,您可以尝试

 [SwaggerResponse(200, typeof(CustomModel))]
Run Code Online (Sandbox Code Playgroud)

并且您另外为该响应类型添加注释作为可选的第三个参数

[SwaggerResponse(200, typeof(CustomModel), "returns a new id of the bla bla")]
Run Code Online (Sandbox Code Playgroud)

注意:该属性在命名空间Swashbuckle.AspNetCore.Annotations 中

  • 这需要 NSwag.Annotations。 (2认同)
  • 对于 .NET 框架(不是 .NET Core),要使用的 Swashbuckle 命名空间是: using Swashbuckle.Swagger.Annotations (2认同)