Abstract classes on client generated code from swagger spec API net core

1.7k views Asked by At

I have an issue with my errors base class on my api. I used this options to see it working on documentation. But when I use the swagger json to generate Rest Code on https://editor.swagger.io it generates the 3 classes, BaseException (abstract), Error and Warning. when I use the respective code, on my responses comes a list of BaseException but always show me the base only information

exceptions:[
    {
      "severity": "Warning",
      "message": "warning message"
    },
    {
      "severity": "Error",
      "message": "testing"
    }
]

and if I put it as abstract

[DataContract]
    [JsonConverter(typeof(JsonSubtypes), "BaseException")]
    [JsonSubtypes.KnownSubType(typeof(ErrorData), "Error")]
    [JsonSubtypes.KnownSubType(typeof(WarningData), "Warning")]
    public abstract class BaseException : IEquatable<BaseException>
    {

another exceptions is raised:

Could not create an instance of type Api.Test.Client.Model.BaseException. Type is an interface or abstract class and cannot be instantiated. Path 'severity', line 488, position 17. 

I tried to maintain the generated class structure but with no luck, because always return the BaseException content and the discriminator on classes are null (I don't know why)

how can I fix this? thank you!

1

There are 1 answers

0
manuc66 On BEST ANSWER

The second parameter of JsonConverter attribute should be the discriminator field, in you JSON sample it should be severity so the BaseException class should be defined this way:

[DataContract]
[JsonConverter(typeof(JsonSubtypes), "severity")]
[JsonSubtypes.KnownSubType(typeof(ErrorData), "Error")]
[JsonSubtypes.KnownSubType(typeof(WarningData), "Warning")]
public abstract class BaseException : IEquatable<BaseException>
{

See documentation at : https://manuc66.github.io/JsonSubTypes/