Using NSwag to generate a C# client incorrectly creates 2x partial classes with the same name, in the same file

Viewed 657

I'm trying to generate an NSwag C# Client, from an OpenAPI json file.

When I do this, I do get a client file generated, but it doesn't compile. It has created 2x partial classes in the same .cs file.

enter image description here

Now, if I change one of these class names to anything else, the file can now compile:

enter image description here

No errors - compiles OK.

So my question is: why is this doing it?

Here's a picture of my Swagger UI (this was generated with Swashbuckle, not NSwag):

enter image description here

So this means I have 2x controllers in the project:

  • HomeController
  • DocumentsController

Is there some trick to fixing this?

I used the following command line, to generate the client:

dotnet-openapi --updateProject .\MyProject.csproj http://localhost:5100/swagger/v1/swagger.json

Dotnet-openapi is using NSwag CSharpClientGenerator "under the hood", as far as I believe.

I'm happy to use any other tool to generate a C# client.

1 Answers

I had this problem and was able to solve it after staring at the code for some time. The issue was that my endpoint had an underscore (_) in the uri, which nswag apparently don't get along with;

[HttpPost("a_bad_uri_with_underscore")]
public void SomeMethod() => _someHandler.Execute();

Typing an underscore was a mistake, my intention was to use dash (-) so once that was changed it worked.

[HttpPost("a-working-uri-with-dash")]
public void SomeMethod() => _someHandler.Execute();
Related