Search code examples
c#yamlopenapinswag

How do return the json output properly by nswag


I am using nswag to generate the server side c# controller code by a yaml file.

I can call the endpoint successfully via an API caller (such as postman).

The main problem is that the output is not what I am expecting.

To simplify the problem,

Let say I have the following yaml definition to be returned by a GET endpoint.

Car:
  type: object
  required:
    - id
    - color
    - type
  properties:
    id:
      type: integer
      format: int64
    color:
      type: string
      enum: [red, yellow]
    type:
      type: string
      enum: [a, b]

GetCarByIdResponse:
  type: object
  required:
    - car
  properties:
    car:
      $ref: '#/components/schemas/Car'

Then, nswag generates the following c# server controller code for me to implement,

    public override async Task<ActionResult<GetCarByIdResponse>> GetCarById(long id)
    {
        ...
        return Ok(new GetCarByIdResponse() { car = ...});
    }

In https://editor.swagger.io/ (with the yaml definition), I can see that the response should be something like below,

{
  "car": {
    "id": 1,
    "color": "yellow",
    "type": "a"
  }
}

But when I actually call the GET endpoint, the output is something I am not expecting.

{
  car: {
    id: 1,
    color: 1,
    type: 0
  }
}

There are 2 main problems:

  1. For valid json format, the field name needs double quotes (for examples, it should be "color" instead of color)

  2. For the enum field, it is showing the enum integer value (in the generated c# code), but not the string for human readability.

Is there any way for the nswag generated c# server code to generate something matched with what is shown in the https://editor.swagger.io/ as a valid json output?

Update (on 2024-09-27):

Please ignore the double quotes issue, when I checked the raw response, they are there. It looks like that the pretty output will hide the double quotes.


Solution

  • Finally figured it out.

    I need to add enum converter explicitly in order to handle the enum when building the server service.

    .AddControllers().AddJsonOptions(x => x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()))
    

    A bit surprised nswag does not generate server code which can handle the enum string by default. This may not be the best solution but the only one I can find at the moment.