All Articles

Add new OpenAPI service reference to .NET Core 3.0 projects

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”.

Image displaying how to start the add dialog

I was presented with a simple dialog without much details or guidance.

The add dialog from Visual Studio

A few seconds after hitting OK it shows up in the list:

Showing the overview of added OpenAPIs

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.

Default settings is not what I wanted

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.


Looking at the code again I noticed that its generated by NSwag. Googeling that quickly lead me to the NSwag github. Reading up on this toolchain I found the options available in the source code.

Notice that this file is a derived class of ClientGeneratorBaseSettings, so there are a few more settings available.

How to use the Generator Settings

You could add them to the textbox in the add dialog, but I quickly favoured editing the csproj file manually like this:

How to edit the csproj

    <OpenApiReference Include="OpenAPIs\swagger.json" CodeGenerator="NSwagCSharp" Namespace="PetStore.Client">

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: