1 am using c# NSwag.AspNetCore. And I have a polymorphic model. The definition is:
components:
schemas:
TestModel:
type: object
discriminator:
propertyName: $type
mapping:
subModel1: '#/components/schemas/SubModel1'
subModel2: '#/components/schemas/SubModel2'
properties:
id:
type: string
readOnly: true
SubModel1:
type: object
properties:
substrateBuildVersion:
type: string
allOf:
- $ref: '#/components/schemas/TestModel'
SubModel2:
type: object
properties:
isLevOrchestrated:
type: boolean
allOf:
- $ref: '#/components/schemas/TestModel'
the api definition is:
/// <inheritdoc />
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
public override async Task<ActionResult<TestModel>> TestAPI2([FromBody] TestModel body = null, CancellationToken cancellationToken = default(System.Threading.CancellationToken))
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
{
await Task.Delay(1).ConfigureAwait(false);
TestModel model = (SubModel1)body!;
return Ok(model);
}
/// <inheritdoc />
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public override async Task<ActionResult<ICollection<TestModel>>> TestAPI3(CancellationToken cancellationToken = default)
{
await Task.Delay(1).ConfigureAwait(false);
TestModel model = new SubModel1
{
Id = "test",
SubstrateBuildVersion = "test",
};
return Ok(new List<TestModel> { model });
And I found that if the response is a collection (TestAPI3), the response will contain $type, but if not, the response will not contain $type.
{
"substrateBuildVersion": "test",
"id": "test"
}
{
"substrateBuildVersion": "test",
"id": "test",
"$type": "subModel1"
}
Why have this result? what if I want the single object has the $type too?
what if I want the single object has the $type too?
New contributor
Ruoru Yan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.