ASP. NET Core Webapi using swagger to generate API documentation look, this is enough.

Source: Internet
Author: User

Introduction

After the API development is done using ASP., writing the API documentation is a pain to the programmer, but the document must be written, and the document's format, if not specifically required, will depend entirely on the developer's mood. Or a little bit more, or simply. So is there a quick and efficient way to build API documentation? The answer is yes, swagger is one of the most popular rest APIs document generation tools!

Why use swagger as a rest APIs document generation tool
    1. Swagger can generate an interactive API console that developers can use to quickly learn and experiment with the API.
    2. Swagger can generate client SDK code for implementations on a variety of different platforms.
    3. Swagger files can be automatically generated from code annotations on many different platforms.
    4. Swagger has a strong community with many powerful contributors.
How do I use Swagger to generate API documentation in ASP.
    1. Swashbuckle.aspnetcore is an open source project for generating Swagger documentation for the ASP. NET Core Web API.
    2. Nswag is another open source project for integrating the Swagger UI or redoc into the ASP. NET Core Web API. It provides a way to generate C # and TypeScript client code for the API.
Let's take swashbuckle.aspnetcore as an example to show you swashbuckle what are the components?
    • Swashbuckle.AspNetCore.Swagger: Exposes the Swaggerdocument object as the Swagger object model and middleware for the JSON endpoint.
    • Swashbuckle.AspNetCore.SwaggerGen: The Swagger generator that generates swaggerdocument objects directly from routes, controllers, and models. It is typically combined with the Swagger endpoint middleware to automatically expose Swagger JSON.
    • Swashbuckle.AspNetCore.SwaggerUI:Swagger the embedded version of the UI tool. It explains Swagger JSON to build a rich, customizable experience that describes the functionality of the Web API. It includes built-in test tools for public methods.
How do I install swashbuckle using vs2017?
    • To install from the Package Manager console window
    • Go to view > Other Windows > Package Manager console.
    • Navigate to the directory that contains the Todoapi.csproj file
    • Please execute the following command · Install-package Swashbuckle.aspnetcore
    • From the Manage NuGet Packages dialog box:
    • Right-click the project in Solution Explorer > Manage NuGet Packages
    • Set package source to "nuget.org"
    • Enter "Swashbuckle.aspnetcore" in the search box
    • Select the Swashbuckle.aspnetcore package from the Browse tab, and then click Install
Adding and configuring Swagger middleware

First introduce a namespace:

using Swashbuckle.AspNetCore.Swagger;

Add the Swagger generator to the service collection in the Startup.configureservices method:

//注册Swagger生成器,定义一个和多个Swagger 文档services.AddSwaggerGen(c =>{     c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });});

In the Startup.Configure method, enable middleware to serve the generated JSON document and Swagger UI:

//启用中间件服务生成Swagger作为JSON终结点app.UseSwagger();//启用中间件服务对swagger-ui,指定Swagger JSON终结点app.UseSwaggerUI(c =>{    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");});

Launch the app and navigate to http://localhost:<port>/swagger/v1/swagger.json . The resulting document describing the endpoint is shown in the following JSON format.

The http://localhost:<port>/swagger Swagger UI can be found. Browse the API documentation through the Swagger UI as shown below.

To provide the Swagger UI at the root () of the app http://localhost:<port>/ , RoutePrefix set the property to an empty string:

app.UseSwaggerUI(c =>{    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");    c.RoutePrefix = string.Empty;});
Advanced usage of swagger (custom and extended) use swagger to add descriptive information to API documentation

The AddSwaggerGen following configuration actions are added to the method, such as author, license, and description information:

//注册Swagger生成器,定义一个和多个Swagger 文档services.AddSwaggerGen(c =>{    c.SwaggerDoc("v1", new Info    {        Version = "v1",        Title = "yilezhu‘s API",        Description = "A simple example ASP.NET Core Web API",        TermsOfService = "None",        Contact = new Contact        {            Name = "依乐祝",            Email = string.Empty,            Url = "http://www.cnblogs.com/yilezhu/"        },        License = new License        {            Name = "许可证名字",            Url = "http://www.cnblogs.com/yilezhu/"        }    });});

The Wagger UI displays the version information as shown in:

To prevent the blog from being reproduced, do not retain the link to this article, specifically to join this article link: https://www.cnblogs.com/yilezhu/p/9241261.html

To add a comment to an interface method

Everyone first click on the API, expand as shown, can not comment ah, how to add comments?

Use three/Add a document comment as shown below

/// <summary>/// 这是一个api方法的注释/// </summary>/// <returns></returns>[HttpGet]public ActionResult<IEnumerable<string>> Get(){     return new string[] { "value1", "value2" };}

Then run the project and go back to Swaggerui to see if the comment appears.

Still no show, don't worry, look down!

Enable XML annotations

You can enable XML annotations using the following methods:

    • Right-click the project in Solution Explorer and select Properties
    • View the XML document file box under the output section of the Build tab

When XML annotations are enabled, debug information is provided for public types and members that are not logged. If there are many warning messages, for example, the following message indicates a violation of warning code 1591:

warning CS1591: Missing XML comment for publicly visible type or member ‘TodoController.GetAll()‘

What if you have obsessive-compulsive disorder and want to cancel the warning? Can be canceled as shown

Note the path to the XML document file that was generated above,

  Note:

? 1. File names and paths are case-sensitive for Linux or non-Windows operating systems.   For example, the "swaggerdemo.xml" file is valid on Windows but is not valid on CentOS.

? 2. Get the application path, it is recommended to use Path.getdirectoryname (typeof). Assembly.location) this way

Registers the swagger generator, defining one and more swagger document services. Addswaggergen (c + = {C.swaggerdoc ("v1", new Info {Version = "V1", Title = "Yilezhu ' s API", Description = "A Simple example ASP. NET Core Web AP                        I ", Termsofservice =" None ", contact = new Contact { Name = "Happy Wish", Email = string. Empty, Url = "http://www.cnblogs.com/yilezhu/"}, License = n EW License {name = "license Name", URL = "http://www.cnblogs.co                m/yilezhu/"}}); Sets the XML document comment path for the Swagger JSON and ui var BasePath = Path.getdirectoryname (typeof (Program). assembly.location)///Get the directory where the application is located (absolute, not affected by the working directory, we recommend this method to get the path) var Xmlpath = Path.Combine (basePath, "Swaggerdemo.xml");            C.includexmlcomments (Xmlpath); });

Rebuild and run the project see if the comment appears.

It can be concluded that the Swagger UI displays the inner text of the elements of the comment code above <summary> as a large annotation of the API!

Of course you can also add the remarks element to the Create action method document. It can supplement the <summary> information specified in the element and provide a more reliable Swagger UI. <remarks>element content can contain text, JSON, or XML. The code is as follows:

 /// <summary> /// 这是一个带参数的get请求 /// </summary> /// <remarks> /// 例子: /// Get api/Values/1 /// </remarks> /// <param name="id">主键</param> /// <returns>测试字符串</returns>           [HttpGet("{id}")] public ActionResult<string> Get(int id) {       return $"你请求的 id 是 {id}"; }

Regenerate the next item, when good to Swaggerui see as follows:

Using the Swaggerui Test API interface

Below we have a small example through the Swaggerui Debug interface bar

    1. Click on an API interface to test and click on the "Try it Out" button on the left and right side of the parameters
    2. In the parameter text box that appears, enter a parameter, as shown in, input parameter 2
    3. Click the Execute button and the formatted response shown below will appear as shown in

Well, today's tutorial on ASP. NET Core Webapi using swagger to generate API documentation see this is enough. Hopefully it's helpful to learn how to use swagger to build API documentation in ASP.

Summarize

? This article starts with the pain of manually writing API documentation, and then leads to swagger, a tool that automatically generates an API description document! Then, with the easy-to-understand text combined with the images, we demonstrated how to generate API documentation using Swaggerui in an ASP. NET Core Webapi. Finally, we introduce some advanced usage of swagger in ASP. We hope to help you use swagger in ASP.

ASP. NET Core Webapi using swagger to generate API documentation look, this is enough.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.