This How-To describes how to inject dependency to HttpClient you generated for PetStore API with OpenAPI (Swagger) Connected Service to ASP.NET Core application. The sample code is available in here.
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:
That’s it! We have injected generated client for PetStore API to ASP.NET Core application via the dependency injection (DI) software design pattern.
Enjoy coding with the Coding Machine…
Top comments (2)
Hi. I have a question,
if my response is a Ok and BadRequest,
how can i get the data this request?
If you are generating with NSwag for your API controller - add attributes and return the object from the action - something like this:
In this case NSwag will know how to interpret your responses - see in generated code how to retrieve error details from ApiException generated client will throw for any non OK response you defined.