Recently I talked about some of the new features in .NET 5.0 and preview versions of Visual Studio 16.8 and 16.9 with respect to ASP.NET Core Web API Projects. The first announcement I mentioned was the built-in support for OpenAPI and Swagger UI via Swashbuckle in the new ASP.NET Core 5 Web API Project Template, and the other announcement was a new feature introduced in Visual Studio 2019 that allows you to publish the web API to Azure API Management Services as part of the flow of publishing the ASP.NET Core Web API. Both of these tutorials mention Swashbuckle to generate the OpenAPI Specification Document. If you're generating an OpenAPI Specification Document for your ASP.NET Core Web API, you can use this same document to generate a client to consume your web API, which is what I will demonstrate in this ASP.NET Core Web API tutorial.

Sample Weather Forecast ASP.NET Core Web API

This tutorial assumes you have created a new ASP.NET Core 5 Web API project, which includes a sample weather forecast API that uses Swashbuckle to generate both an OpenAPI Specification Document and Swagger UI to explore and test the API.

I only want to make one change to this project, which I called WebApi. I want to modify the HTTPGet Attribute on the Get() method of the WeatherForecastController to include a route name of "GetForecast" as shown below.


[HttpGet(Name = "GetForecast")]
public IEnumerable Get()
{
    var rng = new Random();
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
    })
    .ToArray();
}

This route name gets added to the OpenAPI Specification Document as an operationId which will be used as a method name on the client generated in Visual Studio. If this isn't clear, it will be after we generate the client that will consume this web API.

Run the Web API Project to launch a browser that will display the Swagger UI. Click on the link to the swagger.json file in the Swagger UI to display the OpenAPI Specification Document. Save the file to disk. Remember where you save the swagger file, because we will be using the file to generate the client to consume the web API.

Create .NET Core 5.0 Console Application

Create a .NET Core 5.0 Console Application, ClientApi, in the same solution as the ASP.NET Core 5 Web API project. The console application will consume the sample weather service API. Right-click "dependencies" and choose Add Connected Service. From here we want to add an OpenAPI Service Reference. Navigate to the Add new API service reference dialog and browse for the swagger file you saved earlier. Don't worry about adding a namespace and other additional settings as we will add these directly to the Visual Studio project file. Click "Finish" to watch Visual Studio 2019 generate a client for the ASP.NET Core Web API using the swagger file (e.g. OpenAPI Specification Document).

Visual Studio Code Generation Web API Client

Add New OpenAPI Service Reference Visual Studio 2019

Modify Code Generation Options in Visual Studio Project File

I like to add the code generation options directly to the Visual Studio project file. Right-click the project file of the .NET Core 5.0 Console Application and choose "Edit Project File". You will see a section that references the swagger.json file we imported to generate the API client. You will also see the name of the code generator, NSwagCSharp.


<ItemGroup>
  <OpenApiReference Include="..\api\swagger.json">
    <CodeGenerator>NSwagCSharp</CodeGenerator>
    <Link>OpenAPIs\swagger.json</Link>
    <Namespace>ClientApi.Services</Namespace>
    <ClassName>WeatherServiceClient</ClassName>
    <OutputPath>WeatherServiceClient.cs</OutputPath>
  </OpenApiReference>
</ItemGroup>

There are a number of options you can add for the code generator. At a minimum, I like to specify the namespace, class name, and output path for the OpenAPI client generated by Visual Studio using NSwag. We'll be importing this namespace and using the class name when we consume the API in our .NET Core 5.0 Console Application.

Save the project file when you're done editing it. I typically delete the "bin" and "obj" directories in my Visual Studio project and re-build the project. This causes the code generator to run again, using the code generation options we just added to the project file.

Using the NSwag Code Generated OpenAPI Client

We're now ready to consume the ASP.NET Core 5 Web API using the client generated by NSwag based on the OpenAPI Specification Document. Shown below is a simple .NET Core 5 Console Application that calls the ASP.NET Core Web API to get the weather forecast.

using ClientApi.Services;
using System.Net.Http;
using System.Threading.Tasks;

namespace ClientApi
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var httpClient = new HttpClient();
            var client = new WeatherServiceClient(
                 "https://localhost:44322",
                 httpClient);
            var forecast = await client.GetForecastAsync();

            foreach(var item in forecast)
            {
                Console.WriteLine($"{item.Summary}");
            }
        }
    }
}

You can see how the code generation options we specified in our Visual Studio project impact the code we have written. First, the class name is WeatherServiceClient, which is the name we specified in the code generation options. We import the ClientApi.Services namespace, which is also the namespace we specified for the client in the code generation options.

In addition, notice the name of the method we are calling on the client to retrieve the weather forecast, GetForecastAsync. "GetForecast" is the route name we added to the ASP.NET Core Web API. As mentioned above, this route name gets added to the OpenAPI Specification Document as an operationId, which is used to generate the name of the method on the client.

You can run the console application to consume the web API. Make sure you specify both projects as startup projects for your solution.

Wrap Up

If this is your first time using code generation to create an OpenAPI client in Visual Studio, congratulations. You've accomplished a lot during the tutorial.

First, we created an ASP.NET Core 5 Web API using Visual Studio. The new Web API template now includes Swashbuckle.AspNetCore and is configured to create the OpenAPI Specification Document and Swagger UI. We added a custom route name to the Web API, which generated an operationId in the swagger file. This operationId was used as the name of the method on our code-generated API client. We then saved the swagger.json file from the link on the Swagger UI so we could later use it for code generation.

We then created a .NET Core 5 Console Application in the same solution and added an OpenAPI service reference using the OpenAPI Specification Document we saved earlier. We customized the code generation options and then generated the new API client.

Finally, we used the code generated API client in the console application to consume the web API!