How to reuse classes when generating an OpenAPI client?

1.4k Views Asked by At

Let's say I have this class defined:

public class Animal
{
   public int RegId {get;set;}
   public string Name {get;set;}
}

And I need to expose it to an remote part of my system ( a client app in another location, for example ) and I decided to use OpenAPI to make the communication.

The controller code is something like:

[HttpGet("GetLivingCargo")]
public async Task<IEnumerable<Animal>> GetLivingCargo()
{
    return await pFacade.GetLivingCargo();
}

Swagger generates the documentation all well. When I generate the API client to use in the remote app, all times I have that class duplicated (so there's my original class and the generated client's exactly equal class).

How I can avoid it, without having to manually write the API client myself to use my original class?

1

There are 1 best solutions below

0
On BEST ANSWER

Finally I found a way to make NSwagStudio reuse my Model classes.

Step-by-Step:

  1. Get the OpenAPI spec URL
  2. Make it create an local copy to double check if is the correct spec
  3. Mark "C# Client" on Outputs section of the screen (cannot put an image now because the firewall blocks ImgUr.com)
  4. On Settings tab, two configuration need to be changed:
    • Additional Namespace Usages: put the namespace list of the classes you want to reuse (comma-separated)
    • Generate DTO Types: UNCHECK
  5. Generate.

For those who do not want an all-or-nothing approach, with Generate DTO Types checked, you can exclude certain types by filling the (comma-separated) list of types to be excluded in Exclude Type Names configuration setting.