如何让Swagger显示从API返回的对象的示例?

Cas*_*ton 9 .net c# api swagger swashbuckle

我是第一次创建一组API.这是其中一种方法:

    // GET: api/Doors/0
    /// <summary>
    /// Get a list of all doors for a given organization.
    /// </summary>
    /// <param name="organizationSys">The Organization ID for which all doors should be retreived.</param>
    /// <returns></returns>
    [Route("{organizationSys:int}")]
    public IHttpActionResult Get(int organizationSys)
    {
        try
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("@OrganizationSys", organizationSys);
            List<Door> doors = Repository<Doors>.GetList("WHERE OrganizationSys = @OrganizationSys", parameters).ToList();
            if (doors == null || doors.Count() == 0)
                return Content(HttpStatusCode.NotFound, RejectionMessage.NoItemsFound);

            return Ok(doors);
        }
        catch (Exception ex)
        {
            return Content(HttpStatusCode.BadRequest, ex.Message);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我已经为这个端点设置了一个单元测试,它运行得很好.但是,我确实有一个问题.

在Swagger中,我想展示一个将返回的数据对象的示例.该方法唯一的返回类型是IHttpActionResult如此,我并不惊讶它没有在Swagger中显示数据模型.那么,我需要使用此方法更改什么才能使返回对象(在本例中List<Door>)更加明显?

Swashbuckle支持这个吗?

谢谢!

que*_*atl 15

这应该是非常简单的:

[Route("{organizationSys:int}")]
[ProducesResponseType(typeof(List<Door>), 200)]
[ProducesResponseType(typeof(string), 400)]
public IHttpActionResult Get(int organizationSys)
Run Code Online (Sandbox Code Playgroud)

请注意,由于您有2个退出点:一个带有数据的正常返回和catch返回错误消息,我在上面的示例中定义了两种可能的结果类型:

  • http:200(OK)用 List<Door>
  • http:400(BadRequest)用 string

Swashbuckle Swagger基础设施将阅读该内容,并为这些案例提供非常粗略的数据示例.

但是,如果您需要更详细的示例(即具有一些合理的字段值),那么您将必须实现"示例提供程序".有关详细信息和快速教程,请参见此处:

[SwaggerRequestExample(typeof(DeliveryOptionsSearchModel), typeof(DeliveryOptionsSearchModelExample))]
public async Task<IHttpActionResult> DeliveryOptionsForAddress(DeliveryOptionsSearchModel search)
Run Code Online (Sandbox Code Playgroud)

public class DeliveryOptionsSearchModelExample : IExamplesProvider
{
  public object GetExamples()
  {
    return new DeliveryOptionsSearchModel
    {
        Lang = "en-GB",
        Currency = "GBP",
        Address = new AddressModel
        {
            Address1 = "1 Gwalior Road",
            Locality = "London",
            Country = "GB",
            PostalCode = "SW15 1NP"
        },
        Items = new[]
        {
            new ItemModel
            {
                ItemId = "ABCD",
                ItemType = ItemType.Product,
                Price = 20,
                Quantity = 1,
                RestrictedCountries = new[] { "US" }
            }
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

示例提供程序以一种非常简单的方式工作:无论提供程序返回什么,它都被序列化为JSON并作为给定数据类型的示例返回.就像那样.

现在,如果您的方法返回DeliveryOptionsSearchModel,提供者将直接使用上面的数据.

或者,如果您的方法返回一个更大的对象,由DeliveryOptionsSearchModel其他人组成,那么Swagger将使用此提供程序作为响应exaple的一部分,并将其他提供程序(或默认粗略示例)用于大对象的所有其他部分.


以上所有内容均为Net Core.

如果使用'normal'Net 4.5/4.6/4.7,那么这些方法不可用,因为Attribute类不存在.在AspMvc for Net 4.x中,只有[ResponseType(typeof(..))]属性允许定义单个返回类型.这在大多数时候都没问题.但是,如果您确实需要区分返回类型而不是响应代码,或者如果您需要提供好的示例,则这是一个问题.

然而!一些好人已经解决了.看到这篇文章.它描述了NuGet Swagger.Examples,我相信它是非核心的,它的目标是提供更好的结果描述.

它定义了另一个属性 - [SwaggerResponse(HttpStatusCode.OK, Type=typeof(IEnumerable...定义可能的结果代码和结果类型,并为Swagger提供插件以使用该属性.

它还提供了另一个属性,[SwaggerResponseExample...即allwos定义结果示例提供程序,它可以提供数据的自定义良好示例,就像上面针对Core描述的IExampleProvider一样.整齐!


Gab*_*ada 7

对于 ASP.NET WebApi2,您可以使用属性 SwaggerResponse。您可以指定状态代码和返回类型。

[SwaggerResponse(System.Net.HttpStatusCode.OK, Type = typeof(List<Door>))]
[SwaggerResponse(System.Net.HttpStatusCode.NotFound, Type = typeof(string))]
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到更多信息:https : //mattfrear.com/2015/04/21/generating-swagger-example-responses-with-swashbuckle/