OpenAPI (Swagger) Connected Service is a Visual Studio extension to generate C# HttpClient code for OpenAPI (formerly Swagger) web services with NSwag. Simply put, it is like kind old Add Service Reference for WCF or Add Web Reference for WSDL, but for JSON API we all deal with nowadays.
Follow 5 steps below to achieve this:
Step 1. Generate C# HttpClient class for PetStore API in your ASP.NET Core MVCweb application using OpenAPI (Swagger) Connected Service. See Getting Started section to install and run this Visual Studio extension.
Step 2. Add new file PetStoreClient.cs and make sure the class is marked as partial and has the same name and namespace as generated public partial class Client in PetStoreClient.Generated.cs. Also define the interface IPetStoreClient. The idea behind using the interface is to separate the methods you see where your client is used from what you don’t want to expose. In this sample we just expose the method to retrieve the number of pets sold by the store. So we define the method GetSoldPetsCount, which internally uses generated method for GET pet/findPetsByStatus endpoint. That is how it might look like:
Step 3. Now let’s use HttpClientFactory to inject the IPetStoreClient. Go to Startup.cs and add this to ConfigureServices method:
Step 4. In Index action in HomeController.cs let’s inject IPetStoreClient and pass the number of sold pets to the View:
Step 5. To display the number of sold pets on the default site page add this code to View\Home\Index.cshtml:
Enjoy coding with the Coding Machine…