提问者:小点点

Swagger SwashBuckle抽象类留档


我有WebAPI请求模型与属性:

public List<Feature> Features { get; set; }

Feature是一个抽象类。我将从它派生许多类:

public abstract class Feature
{
    public string Title { get; set; }
}

public class ImageFeature : Feature
{
    public string ImageUrl { get; set; }
}

显然,Swash巴克尔只识别Feature属性并相应地生成留档。我如何显式声明Feature类的可能实现,以便Swash巴克尔生成正确的文档?是否有一些我可以使用的属性,例如:

[SwaggerResponseType(typeof(ImageFeature))]
[SwaggerResponseType(typeof(AnotherFeature))]
public abstract class Feature

共2个答案

匿名用户

看看这个:http://swashbuckletest.azurewebsites.net/swagger/ui/index#! /InheritanceTest/InheritanceTest_Get

这是控制器后面的代码:https://github.com/heldersepu/SwashbuckleTest/blob/911bf68e0cf6af3ee5d8278e6dd988eda8c4dc8d/Swagger_Test/Controllers/InheritanceTestController.cs

using System.Web.Http;

namespace Swagger_Test.Controllers
{
    public abstract class Feature
    {
        /// <summary>We all need a Title</summary>
        public string Title { get; set; }
    }

    public class ImageFeature : Feature
    {
        /// <summary>Here goes your image URL</summary>
        public string ImageUrl { get; set; }
    }

    public class InheritanceTestController : ApiController
    {
        public ImageFeature Get([FromUri]ImageFeature imageFeature)
        {
            return imageFeature;
        }

        public ImageFeature Post(ImageFeature imageFeature)
        {
            return imageFeature;
        }
    }
}

匿名用户

没有特定的请求模型。可能的选择是编写操作过滤器

这是伪代码

    public class RequestModelExtentionOperator: IOperationFilter    
        {                 
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.operationId == "Controller_ActionName")  // controller and action name
        {
           var refSchema = schemaRegistry.GetOrRegister(typeof(List<ImageFeature>));
                //here you can create a new Parameter of type Array
var param=new Parameter 
                    {
                        name = "Features",
                        @in = "formData",
                        required = true,
                        type = "array"
                    };
            param.PopulateFrom(schema);
operation.parameters = new[]{ param };
        }
    }            
            }
    }

然后我们可以设置操作过滤器

httpConfiguration
     .EnableSwagger(c => c.SingleApiVersion("v1", "A title for your API"))
         {
             c.OperationFilter<RequestModelExtentionOperator>();
         });

希望有帮助