如何在swagger生成中将OneOf替换为AnyOf

问题描述 投票:0回答:1

我有一个生成 swagger 的 C# 代码

    services.AddSwaggerGen(options =>
    {
        options.UseOneOfForPolymorphism();
        options.SelectDiscriminatorNameUsing(_ => "messageType");
        options.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "MyTitle",
            Description = "MyDescription",
            Contact = new OpenApiContact
            {

                Name = "MyName",
                Email = "[email protected]"

            }

        });
        options.UseAllOfToExtendReferenceSchemas();
    });

如何在生成的 swagger 中将 UseOneOfForPolymorphism 方法生成的“OneOf”替换为“AnyOf”?

c# swagger asp.net-core-webapi openapi
1个回答
0
投票

我们可以通过在生成的 swagger 文档中使用自定义

OneOf
方法将
AnyOf
替换为
SchemaFilter

这里有一个关于在asp.net core中实现

OneOf
的链接。

我们可以按照下面的建议将

OneOf
替换为
AnyOf

测试结果

enter image description here

我的测试代码

1。 OneOfToAnyOfSchemaFilter.cs

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace WebApplication1
{
    public class OneOfToAnyOfSchemaFilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            if (schema.OneOf != null && schema.OneOf.Any())
            {
                schema.AnyOf = schema.OneOf;
                schema.OneOf = null;
            }
        }
    }
}

2。程序.cs

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using WebApplication1;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.UseAllOfForInheritance();
    options.UseOneOfForPolymorphism();

    options.SelectSubTypesUsing(baseType =>
        typeof(Program).Assembly.GetTypes().Where(type => type.IsSubclassOf(baseType))
    );

    //options.UseOneOfForPolymorphism();
    options.SelectDiscriminatorNameUsing(_ => "messageType");
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "MyTitle",
        Description = "MyDescription",
        Contact = new OpenApiContact
        {
            Name = "MyName",
            Email = "[email protected]"
        }
    });
    options.UseAllOfToExtendReferenceSchemas();
    // Register our custom SchemaFilter
    options.SchemaFilter<OneOfToAnyOfSchemaFilter>();
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

3. WeatherForecast.cs

namespace WebApplication1
{
    public class WeatherForecast
    {
        public DateTime Date { get; set; }

        public int TemperatureC { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

        public string? Summary { get; set; }
    }

    public class WeatherForecastWithLocation : WeatherForecast
    {
        public string? Location { get; set; }
    }
}

4。 WeatherForecastController.cs

using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }
        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get() =>
            DateTime.Now.Minute < 30
                ? Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = Random.Shared.Next(-20, 55),
                    Summary = Summaries[Random.Shared.Next(Summaries.Length)]
                })
                : Enumerable.Range(1, 5).Select(index => new WeatherForecastWithLocation
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = Random.Shared.Next(-20, 55),
                    Summary = Summaries[Random.Shared.Next(Summaries.Length)],
                    Location = "London"
                })
                .ToArray();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.