There are multiple ways to generate a C# client based on an OpenAPI specification file. Today I want to show you how this can be done directly inside Visual Studio.
To import an OpenAPI reference, you can right-click on your project and choose Add –> Service Reference:
Choose OpenAPI from the list of possible service references and click on Next:
Now we can specify the details to our OpenAPI JSON file. Click on Finish to generate the client:
It can take some time to generate the client. So be patient.
What is happening behind the scenes?
Let us have a look at all the things that Visual Studio is doing behind the scenes.
First a copy of the OpenAPI json file is imported into our project and stored inside an OpenAPIs folder:
On this JSON file the build action is set to Open API File Reference and specific code generation attributes are configured:
Our updated csproj file looks like this:
Behind the scenes the code generator is using the Microsoft.dotnet-openapi command line tool which uses NSwag in the end.
We can further control what is generated by specifying additional options: