Summary

In the era of front and back separation and the popularity of Restful APIs, perfect interface documents have become a link for communication. Introducing Swagger (also known as OpenAPI) in your project is a good choice to visualize interface data. Will be demonstrated below

  • How to generate Api documents with Nswag
  • How to use NSwagStudio to generate client code and test it

What is Swagger / OpenAPI?

Swagger is a language-neutral specification for describing REST APIs. The Swagger project has been donated to the OpenAPI project, and it is now called the Open API. The two names are used interchangeably, but OpenAPI is preferred. It allows computers and personnel to understand the functionality of the service without direct access to the implementation (source code, network access, documentation). One of the goals is to minimize the effort required to connect to disassociated services. Another goal is to reduce the time required to accurately record services.

Nswag VS Swashbuckle?

There are two more popular .NET Swagger implementation libraries:

  • Swashbuckle.AspNetCore is an open source project for generating Swagger documentation for ASP.NET Core Web API.
  • NSwag is another open source project for generating Swagger documentation and integrating Swagger UI or ReDoc into ASP.NET Core Web API. In addition, NSwag provides methods for generating C # and TypeScript client code for the API.

 

Why did I choose NSwag in .NET core 3.0? NSwag is active, has been updated, and is very powerful. It can be a perfect replacement for Swashbuckle.AspNetCore can refer to: https://github.com/aspnet/AspNetCore.Docs / issues / 4258

First, use Nswag to generate Api documents

step
  1. Create Asp.NET Core Api project and integrate NSwag
  2. Configuration item
  3. Run the project
Create Asp.NET Core Api project and integrate NSwag

We will simply create an ASP.NET core API project. Name it “WebAPIwithSwg”. Based on .NETcore3.0

DotNET_Core_3.0_uses_Nswag_to_generate_Api_documents_and_client_code_1.png

Install nuget package NSwag.AspNetCore

DotNET_Core_3.0_uses_Nswag_to_generate_Api_documents_and_client_code_2.png

Next, configure Nswag service and middleware in Startup.cs file.

Add service in ConfigureServices method

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerDocument (); // Register Swagger service 
        }
Add Nswag middleware in Configure method

 

 

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            app.UseOpenApi (); // Add swagger to generate api document (default route document / swagger / 
            v1 / swagger.json) app.UseSwaggerUi3 (); // Add Swagger UI to the request pipeline (default route: / swagger). 
        }

 

 

Configuration item

DotNET_Core_3.0_uses_Nswag_to_generate_Api_documents_and_client_code_5.png

Run the project

Right-click the project to view in the browser. To view the swagger UI, you need to add “/ swagger” after the url. This example http: // localhost: 54117 / swagger

DotNET_Core_3.0_uses_Nswag_to_generate_Api_documents_and_client_code_6.png

How to use NSwagStudio to generate client code and test it
Providing a GUI interface is a major feature of NSwag. You only need to download and install NSwagStudio to generate client code.
step
  1. Install NSwagStudio now
  2. NSwagStudio configuration, generate client code
  3. Create a test client project
Download and install NSwagStudio

Download NSwag Studio  http://rsuter.com/Projects/NSwagStudio/installer.php  After installation, open NSwag Studio as shown in the figure

DotNET_Core_3.0_uses_Nswag_to_generate_Api_documents_and_client_code_7.jpg

NSwagStudio configuration, generate client code

Select runtime, I choose NETCore30 , switch OpenAPI / Swagger Specification  , enter your Swagger.json path in Specification UR L  , this example: http: // localhost: 54117 / swagger / v1 / swagger.json After entering the path, click  create local copy  button to get json.

DotNET_Core_3.0_uses_Nswag_to_generate_Api_documents_and_client_code_8.png

Continue to configure to generate client code. We first select the ” csharp client ” checkbox, then check off ” Inject Http Client via Constructor (life cycle is managed by caller) “, and finally set the output path and click Generate Files . Proceed as follows

DotNET_Core_3.0_uses_Nswag_to_generate_Api_documents_and_client_code_9.png

At this point the client code has been automatically generated.

DotNET_Core_3.0_uses_Nswag_to_generate_Api_documents_and_client_code_10.jpg

View part of the generated code


 

 

public async System.Threading.Tasks.Task<System.Collections.Generic.ICollection<WeatherForecast>> GetAsync(System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();
            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/WeatherForecast");
    
            var client_ = new System.Net.Http.HttpClient();
            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Method = new System.Net.Http.HttpMethod("GET");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));
    
                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString ();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);
    
                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                                headers_[item_.Key] = item_.Value;
                        }
    
                        ProcessResponse(client_, response_);
    
                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200") 
                        {
                            var objectResponse_ = await ReadObjectResponseAsync<System.Collections.Generic.ICollection<WeatherForecast>>(response_, headers_).ConfigureAwait(false);
                            return objectResponse_.Object;
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); 
                            throw new ApiException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }
            
                        return default(System.Collections.Generic.ICollection<WeatherForecast>);
                    }
                    finally
                    {
                        if (response_ != null)
                            response_.Dispose();
                    }
                }
            }
            finally
            {
                if (client_ != null)
                    client_.Dispose ();
            }
        }

 

 

Create a test client project

Create a control program project and name it ” WebApiClient “.

DotNET_Core_3.0_uses_Nswag_to_generate_Api_documents_and_client_code_13.jpg

Add the automatically generated class “WeatherForecastClient” to the client project, and then install Newtonsoft

DotNET_Core_3.0_uses_Nswag_to_generate_Api_documents_and_client_code_14.jpg

Finally, add test code to the Main function and start using Api.

 

 

 static async System.Threading.Tasks.Task Main(string[] args)
        {

            var weatherForecastClient = new WeatherForecastClient();
            //gets all values from the API
            var allValues = await weatherForecastClient.GetAsync();
            Console.WriteLine("Hello World!");
        }

 

 

Run the client application and call the api

DotNET_Core_3.0_uses_Nswag_to_generate_Api_documents_and_client_code_17.jpg

Of course, if you need to debug the internal code of the api project, you can set breakpoints and enter step by step debugging

DotNET_Core_3.0_uses_Nswag_to_generate_Api_documents_and_client_code_18.jpg

Summary: NSwag functions are much more than this. This article demonstrates how to generate api documents and automatically generated api client code for us to debug, and it can also be used as the corresponding SDK.

Reference: Microsoft official documentation — https: //docs.microsoft.com/zh-cn/aspnet/core/tutorials/getting-started-with-nswag? View = aspnetcore-2.2 & tabs = visual-studio

Orignal link:https://www.cnblogs.com/chengtian/p/11946950.html