What is the process for incorporating OneOf declaration in OpenAPI 3 using Swashbuckle?
add a comment
To incorporate OneOf declaration in OpenAPI 3 using Swashbuckle, follow the steps below:
public class Person
{
public string Name { get; set; }
}
[JsonConverter(typeof(JsonSubtypes), "type")]
[JsonSubtypes.KnownSubType(typeof(Student), "student")]
public class Student : Person
{
public string School { get; set; }
}
[JsonConverter(typeof(JsonSubtypes), "type")]
[JsonSubtypes.KnownSubType(typeof(Employee), "employee")]
public class Employee : Person
{
public string Company { get; set; }
}
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
c.SchemaFilter<OneOfSchemaFilter>();
});
public class OneOfSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
var type = context.Type;
if (type == typeof(Student) || type == typeof(Employee))
{
schema.OneOf = new List<OpenApiSchema>
{
context.SchemaGenerator.GenerateSchema(typeof(Student), context.SchemaRepository),
context.SchemaGenerator.GenerateSchema(typeof(Employee), context.SchemaRepository)
};
}
}
}
[HttpGet("{id}")]
[ProducesResponseType(typeof(Student), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(Employee), StatusCodes.Status200OK)]
public IActionResult GetPerson(int id)
{
if (id % 2 == 0)
{
return Ok(new Student { Name = "John", School = "ABC University" });
}
else
{
return Ok(new Employee { Name = "Jane", Company = "XYZ Inc." });
}
}
Note: The Swashbuckle.AspNetCore.Newtonsoft NuGet package is required for the JsonSubtypes attribute to work with Swashbuckle.
Asked: 2022-05-11 11:00:00 +0000
Seen: 7 times
Last updated: Mar 08 '22