6

I have an endpoint to query details about a "person". Problem, the response could be of type "PhysicalPerson" or "LegalPerson". Both inherit the same "BasePerson" class.

Here is my current code:

[HttpGet("personne/{idpersonne}")]
[ProducesResponseType(typeof(PersonneMoraleType), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(PersonnePhysiqueType), (int)HttpStatusCode.OK)]
public async Task<ActionResult> GetPerson(string idpersonne, [FromQuery] bool avecDocuments = false)
{
    return Ok(await _app.LraConnector.LirePersonne(idpersonne, avecDocuments));
}

Problem, swagger only describe the second type (physical), but if I answer a LegalPerson, it throw a scheme exception. If I use the "BasePerson", both answers works fine, but it's not described properly.

Is there something I can do to improve that?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Echtelion
  • 161
  • 2
  • 7
  • Does this answer your question? [How do I include subclasses in Swagger API documentation/ OpenAPI specification using Swashbuckle?](https://stackoverflow.com/questions/34397349/how-do-i-include-subclasses-in-swagger-api-documentation-openapi-specification) – Matt.G Dec 12 '19 at 14:11
  • 2
    This isn't supported because it doesn't adhere to REST. You're essentially creating an endpoint that returns multiple different resource types. The fact that they all inherit from a common base class is inconsequential. `GetPerson` should return some generic person. If you need a specific person type, then you should have separate endpoints specifically for that purpose. – Chris Pratt Dec 12 '19 at 15:12

2 Answers2

1

I don't think this is supported by swagger because iirc the responses is a dictionary with the statuscode as the key.

If you change one of the responses to return anything else than OK, then it will return your model.

However I dont think this is what you want. You could create one model like this:

public class Person
{
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public PhysicalPerson PhysicalPerson { get; set; }
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public OtherPerson OtherPerson { get; set; }
}

And then bind you data to the correct property and return this object as the 200 response.

0

I was looking for an answer to this today and came across this: https://mattfrear.com/2015/04/21/generating-swagger-example-responses-with-swashbuckle/.

Essentially, you can add multiple SwaggerResponse decorators to your controller method for multiple types, even with the same Http status code. This worked for me.

erionpc
  • 368
  • 3
  • 15