Edit 2020-09-13: Wrote a quick follow-up with my recommendation for generating OpenAPI clients: https://stigrune.dev/follow-up-open-api-reference-in-visual-studio
On .NET Conf 2019 I noticed that support for adding OpenAPI (Swagger) references was added to Visual Studio Core projects. Today I needed a new client, and the API had Swagger documentation. Awesome, time to test the new function.
At first glance it seemed fairly simple. Right click the project and select: “Add -> Service Reference”.
I was presented with a simple dialog without much details or guidance.
A few seconds after hitting OK it shows up in the list:
I was first a bit puzzled, because no files were added to my project. Strange… After a little while I noticed the little “C#” icon on the right side of the previous screenshot. Clicking this popped up a .cs file with all the generated code. This is saved in the obj folder, and is magically included when you build.
But after studying the code, I noticed that the generated client had no interface, and the client class name was “swaggerClient”. Not optimal. I did notice there was a textbox for “Additional code generation options” in the Add dialog, so I tried to hit up the Visual studio documentation. No luck. I could not find any information about this new feature.
Notice that this file is a derived class of ClientGeneratorBaseSettings, so there are a few more settings available.
You could add them to the textbox in the add dialog, but I quickly favoured editing the csproj file manually like this:
<ItemGroup> <OpenApiReference Include="OpenAPIs\swagger.json" CodeGenerator="NSwagCSharp" Namespace="PetStore.Client"> <SourceUri>https://petstore.swagger.io/v2/swagger.json</SourceUri> <ClassName>PetStoreClient</ClassName> <OutputPath>PetStoreClient.cs</OutputPath> <Options>/GenerateClientInterfaces:true</Options> </OpenApiReference> </ItemGroup>
Rebuild the solution and it will generate an interface and a proper class name and filename. The string value in Options will be added when Visual Studio runs the NSwag.exe generator. Be sure to get the formatting correct. More settings can be added by using space as a separator like this:
<Options>/GenerateClientInterfaces:true /ClientBaseClass:ClientBase /UseHttpRequestMessageCreationMethod:true</Options>
My test project for post is available on my GitHub: https://github.com/stigrune/PetStoreOpenAPIReference