【问题标题】:Swagger Swashbuckle Polymorphism doesn't work with interface typesSwagger Swashbuckle 多态性不适用于接口类型
【发布时间】:2022-01-02 09:50:45
【问题描述】:

通过下面的代码,我试图提及替代模式;与响应的类型共享相同的接口

Startup.cs

services.AddSwaggerGen(c =>
{
    c.UseOneOfForPolymorphism();
});

app.UseSwagger();
app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
});

模型

public interface IOutput
{
    string Discriminator { get; }
}

public class OutputA : IOutput
{
    public string Discriminator => GetType().Name;

    public string PropA { get; set; }
}

public class OutputB : IOutput
{
    public string Discriminator => GetType().Name;

    public string PropB { get; set; }
}

控制器

[HttpGet]
[ProducesResponseType(typeof(IOutput), StatusCodes.Status200OK)]
public IActionResult Get()
{
    return Ok();
}

我希望 OutputAOutputB 两种类型都将被列为返回类型, 但只提到了IOutput

或者,如果我将 IOutputinterface 更改为 classabstract class,则 OutputAOutputB 将被列为有效返回类型:

是否由于 RESTFul/API 标准而不受支持?

或者这可以实现吗?

这是一个.NET Core 2.2 项目,使用Swashbuckle.AspNetCore v6.2.3

【问题讨论】:

    标签: asp.net-core asp.net-web-api swagger openapi swashbuckle


    【解决方案1】:

    分享我找到的解决方案,以防万一有人需要。

    这个想法是通过AddSwaggerGen() 通过SelectSubTypesUsing() 显式添加多态关系:

    services.AddSwaggerGen(c =>
    {
        c.UseOneOfForPolymorphism();
        c.SelectSubTypesUsing(baseType =>
        {
            if (baseType == typeof(IOutput))
            {
                return new[]
                {
                    typeof(OutputA),
                    typeof(OutputB)
                };
            }
            return Enumerable.Empty<Type>();
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      • 2016-05-01
      • 2018-08-24
      • 2022-09-24
      相关资源
      最近更新 更多