6

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647

2 Answers2

2

This took a while to figure out. Other answers list setting OperationGenerationMode.SingleClientFromOperationId on the generator somehow, but I couldn't find how to do that. I examined the NSwag source to figure out how to set it.

var document = await OpenApiYamlDocument.FromFileAsync("api.yaml");

var settings = new CSharpClientGeneratorSettings()
{
    ClassName = "MyClient",
};
settings.CSharpGeneratorSettings.Namespace = "MyNamespace";

var generator = new CSharpClientGenerator(document, settings);

// How to Set SingleClientFromOperationId
generator.BaseSettings.OperationNameGenerator = new SingleClientFromOperationIdOperationNameGenerator();

var code = generator.GenerateFile();

File.WriteAllText("client.cs", code);
Ben Adams
  • 121
  • 1
  • 5
1

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();
DaggeJ
  • 2,094
  • 1
  • 10
  • 22