How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio

Before moving forward, let’s learn what NSwag is.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

What is NSwag?

NSwag is a Swagger/OpenAPI 2.0 and 3.0 toolchain for .NET, .NET Core, Web API, ASP.NET Core, TypeScript (jQuery, AngularJS, Angular 2+, Aurelia, KnockoutJS and more) and other platforms, written in C#. The Swagger specification uses JSON and JSON Schema to describe a RESTful Web API. The NSwag project provides tools to generate Swagger specifications from existing ASP.NET Web API controllers and client code from these Swagger specifications.

The definition is a reference from the below link: https://github.com/RSuter/NSwag

What is OpenAPI?

In short, OpenAPI is a project which looks at standardizing how REST APIs are described.

As an example, if you take WSDL which is SOAP-based, it has standards. When you create a .asmx service, its document is generated in the form of XML which tells how to access that service and what operation that service provides. The same way, OpenAPI Initiative (OAI) is trying to standardize the APIs.

Details about this: - https://www.openapis.org/about

Tools

  1. Visual Studio 2017 with ASP.NET Core 2.1
  2. AspNetCore package from NuGet

Topic

  1. Creating ASP.NET Core Application
  2. Adding NSwag.AspNetCore from NuGet
  3. Configuration of NSwag in the startup file
  4. Running Application
  5. Downloading Nswag Studio
  6. Swagger specification
  7. Adding Console app
  8. Using Generated Client to call Web API
  9. Making Change in a Startup project
  10. Run Application to access API using Generated Client
  11. NSwag example with ASP.NET Core via API Explorer
  12. Adding class to DemoClient2 to console project.
  13. Run Application to access API using generated client with ASP.NET Core via API Explorer

Creating Asp.net core Application

 

In this step, we are going to simply create an ASP.NET Core API application. Name it as “WebNSwag.Sample”. While creating it, we are going to choose ASP.NET Core 2.1 Framework.
How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 
 

Adding NSwag.AspNetCore from NuGet

 

In this step, we are going to add NSwag.AspNetCore package from NuGet package to generate the Swagger UI.
 
How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After adding the NSwag.AspNetCore package, the project structure will look something like the below image. 

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

Next, we need to configure the NSwag Services and Middleware in Startup.cs file.

Configuration of NSwag Services and Middleware in the startup file

In this part, we are going to configure services first in ConfigureServices method by adding the AddSwaggerDocument method.

Code snippet of Startup.cs

  1.   public void ConfigureServices(IServiceCollection services)  
  2.   {  
  3. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
  4.       // add services required for Swagger 2.0 generation  
  5.       services.AddSwaggerDocument();   
  6.   }   

After registering the service, next, let us add NSwag middleware in the Configure Method.

Adding UseSwagger and UseSwaggerUi3 Middleware to Configure Method.

Code Snippet of Startup.cs

  1. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  2.  public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  3.  {  
  4.      if (env.IsDevelopment())  
  5.      {  
  6.          app.UseDeveloperExceptionPage();  
  7.      }  
  8.      app.UseMvc();  
  9.   
  10.      // Middleware  
  11.      if (env.IsDevelopment())  
  12.      {  
  13.          app.UseSwagger();  
  14.          app.UseSwaggerUi3();  
  15.      }  
  16.  }  

Now, we are going to save and run the application.

If you are thinking "we have not added any API, how will it generate documentation for it?", then let me tell you that we have default API created with the name ValuesController.

Let’s run this application to check it.

Running Application

After running the application, it will execute the values using API GET method, as shown below.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

Now, to see the documentation part of API, we need to enter the keyword “swagger” to the URL, as shown below.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After entering the URL, you will see the documentation of all HTTP methods (GET, POST, PUT, DELETE) of the API. If you want to share documentation with another team of APIs, you just need to share this URL of Swagger; that’s it.

You can also customize it by adding a description to it.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After generating the Swagger document, now we are going to generate the client code for accessing this API.

For doing that, first, we are going to download NSwag Studio.

Downloading NSwag Studio

To generate the client code for accessing this API with C# console application, here is the link to download: - https://github.com/RSuter/NSwag/wiki/NSwagStudio

After downloading, just install it on your PC. Since Visual Studio does not have support for it, we are using the NSwag Studio to generate the Client Code. Below is the view of NSwag Studio which we have downloaded.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After you see the view of NSwag studio let’s start generating Client code. There are various ways you can do it; let’s first start with “Swagger Specification”

  1. Swagger Specification
  2. Net core via API Explorer
  3. .Net Assembly
  4. Json Schema

The first demo we are going to work with is “Swagger Specification”

Swagger Specification

In Swagger Specification part, we need to provide “swagger.json” file path which we get from “swagger UI” using that swagger.json file NSwag is going to generate Client code.

Sample path: - http://localhost:53846/swagger/v1/swagger.json

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

Next, we are going to provide the swagger.json file path to Swagger Specification URL in NSwag Studio, as shown below.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After entering path just click on Create Local copy button to get json from it. And in the below Swagger Specification Json text area, you will able to see json which is download.

Next step after getting json is to Generate outputs and generate files. We are first going to generate Csharp client, and for doing that we are going to choose “Csharp client” checkbox.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After clicking on Csharp Client you can see various settings which you can configure to generate client class. We are not going to make one change in this setting,  we are just going to uncheck “Inject Http Client via Constructor (life cycle is managed by caller)” because we are not going to inject HTTP client while accessing it.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After unchecking the option, we are going to click on Generate Outputs button to generate client code.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

As you click on Generate Output button it will generate Class as shown in the above snapshot.

Next, we are going to generate Files; before that we are going to set output path where we want this generated file to upload.

For doing that we need to choose Settings tab of Csharp client and then just scroll until the end of it. There you will find “Output file path” and set your output path ,and also you need to provide a name to the file which will be generated.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

Next click on Generate files button and check the folder where you have set output file path.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

Below is the folder where Client code file “DemoClient.cs” is generated via NSwag Studio.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

Next after generating files we are going to create a console app where we are going to add this generated file “DemoClient.cs” and access values API.

Adding Console application

To the same solution, we are going to Add Console Application with Name “ConsoleNSwag”.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After adding project, next, we are going to add generated class “DemoClient” to this Solution.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After adding a reference, you will see some error in console application. For resolving it we need to add Newtonsoft.Json reference to console application.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

Adding Newtonsoft.Json reference to console application from NuGet Package.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After adding missing reference, next we are going to call client in the Main program and test some get method to see if it's working fine.

Using Generated Client to call Web API.

Code Snippet of a Console application

  1. using System;  
  2. using MyNamespace;  
  3.   
  4. namespace ConsoleNSwag  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             Console.WriteLine("Welcome to Nswag Generated Client");  
  11.   
  12.             // Created object of class ValuesClient  
  13.   
  14.             var testClient = new ValuesClient();  
  15.   
  16.             // Call GetAsync Values API  
  17.             var getresult = testClient.GetAsync(1).GetAwaiter().GetResult();  
  18.   
  19.             // Call GetAllAsync Values API  
  20.             var getAllresult = testClient.GetAllAsync().GetAwaiter().GetResult();  
  21.   
  22.         }  
  23.     }  
  24. }  

Now we have both projects in the same solution and we want to run them at once, so then we need to make a small change in project startup.

Making changes in project startup

To set just right-click on a solution -- then click on properties, then you will see properties dialog.

In that dialog set your project startup to “Multiple startup projects” and then in actions for both projects set as “Start”.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After setting it now we are ready to call API using a client which we have generated.

Let’s test the application by running and debugging it.

Run Application to access API using Generated Client

Now in debug mode you can see the response which we got from calling API. For doing this complex thing we have not written a single line of code and it's working fine.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After competing generating client using Swagger Specification and consuming it, next, we are going to have a look at another way of generating client code using “ASP.Net core via API Explorer”.

NSwag example with ASP.Net core via API Explorer

Now we are going to try the second way of generating client code using ASP.Net core via API Explorer. For doing that we need to open our NSwag Studio again.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

In this part, first, we are going to set the Project file path which is the .csproj path of the project (“WebNSwag”) which we have created.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After selecting project path, next, we are going to select CSharp client check box to generate code. And then we are going to uncheck “Inject Http Client via Constructor (life cycle is managed by the caller)”. Because we are not going to inject HTTP client in this demo.

Next, we are going to set the “Output file path” along with the name of the file which we want for the demo. I have named the file as “DemoClient2”.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After setting output file path and entering file name next click on Generate Outputs button to generate Csharp client code.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

After generating client code just click on the Generate Files button to generate a file which will be available on an output file path which you have set.

View of Output folder where the file is Generated.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

Wow, we have generated a client just from Project Reference of .csproj. Now, as we have done already, we can just add this file to console application and consume web API using client generated code.

Adding class to DemoClient2 to console project.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

NoteYou can see we have excluded the first class because the name of the class which is generated is the same; however, we can make changes in settings to generate unique names.

Using Generated Client from ASP.NET Core via API Explorer to call the Web API.

Code Snippet

  1. using System;  
  2. using MyNamespace;  
  3.   
  4. namespace ConsoleNSwag  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             Console.WriteLine("Welcome to Nswag Generated Client");  
  11.   
  12.             // Created object of class ValuesClient  
  13.   
  14.             var testClient = new ValuesClient("http://localhost:53846");  
  15.   
  16.             // Call GetAsync Values API  
  17.             var getresult = testClient.GetAsync(1).GetAwaiter().GetResult();  
  18.   
  19.             // Call GetAllAsync Values API  
  20.             var getAllresult = testClient.GetAllAsync().GetAwaiter().GetResult();  
  21.   
  22.         }  
  23.     }  
  24. }  

Now, to call an API using generate the client, we need to make a small change in the code. We need to pass base API URL via the constructor.

After making the changes, now let’s test the application by running and debugging it.

Run Application to access API using Generated Client

In the below snapshot, we have successfully called values API using generated  client code using NSwag Studio.

How To Use Nswag With ASP.NET Core And Generate Client Code With Nswag Studio 

Finally, in this article, we have learned how to use NSwag to generate a Swagger documentation and client code in simple steps.