Documentation for automatic generation of ASP. NET core Web API using Swagger, online Help test document (ASP. NET core Web API automatically generate documents)

Source: Internet
Author: User
Tags response code

For developers, building a consumer application to understand a variety of APIs is a huge challenge.
Using Swagger's. NET Core package Swashbuckle in your Web API project can help you create good documents and help pages. Swashbuckle can be easily added to a project by modifying the Startup.cs as a set of NuGet packages.
Swashbuckle is an open source project that generates Swagger documents for Web APIs built using ASP. NET Core MVC.
Swagger is a machine-readable, RESTful API presentation layer that supports the creation and discovery of interactive documents, client SDKs, and more.

Swashbuckle has two core components
Swashbuckle.swaggergen: Provides the ability to generate JSON Swagger documents that describe objects, methods, return types, and so on.
Swashbuckle.swaggerui: is an embedded version of the Swagger UI tool that can be customized to describe the functionality of the Web API using the powerful rich text representation of the Swagger UI, and includes built-in public method testing tools.

Create a new ASP. NET Core WebApi project, as shown in the project structure:

Add Swashbuckle with NuGet

1. Tool->nuget Package Manager, Packages Manager console

2. In console input: install-package swashbuckle-pre Press ENTER

3, installation Swashbuckle complete:

4, the installation of Swashbuckle completed background project reference has changed:

5, add more than one in Project.json configuration "Swashbuckle": "6.0.0-beta902":

7. Enable XML annotations, right-click the project in Visual Studio and select Properties under the Output Settings area, click XML documentation file.

9. Set "XmlDoc" in Project.json: true to enable XML annotations.

10. In the Configureservices method of the Startup.cs class, the middleware supply and service are allowed to generate JSON documents and Swaggerui. Add Swaggergen to the Services collection in the Configure method. Configure Swagger to use the generated XML file

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading.Tasks; 5 using Microsoft.AspNetCore.Builder; 6 using Microsoft.AspNetCore.Hosting; 7 using Microsoft.Extensions.Configuration; 8 using Microsoft.Extensions.DependencyInjection; 9 using microsoft.extensions.logging;10 using MICROSOFT.EXTENSIONS.PLATFORMABSTRACTIONS;11 using Swashbuckle.swagger.model;12 namespace dotnetcore_test114 {public class Startup17 {All public Star Tup (Ihostingenvironment env), {var builder = new Configurationbuilder () 21. Setbasepath (env. Contentrootpath) 22. Addjsonfile ("Appsettings.json", Optional:true, Reloadonchange:true) 23. Addjsonfile ($ "appsettings.{ Env. Environmentname}.json ", Optional:true), if (env). Isenvironment ("development")) + {//This would push telemetry data through application Insig HTS pipeline faster, allowingYou to view results immediately.28 Builder. Addapplicationinsightssettings (developermode:true);}30 Builder. Addenvironmentvariables (); Configuration = Builder. Build ();}33 public iconfigurationroot Configuration {get;} //This method gets called by the runtime.         Use this method to add services to the container37 public void configureservices (iservicecollection services) 38 {The//ADD framework services.40 Services. Addapplicationinsightstelemetry (Configuration); Addmvc ();//services. Addlogging (); 45 46//Injection implementation Iswaggerprovider Use the default settings of the. Addswaggergen (); Configureswaggergen (Options =>50 {the options. Singleapiversion (new Info52 {Version = "V1", * * * "Test ASP.N ET Core WebAPIGenerate document (document description) ", Description =" A Simple example ASP. NET Core Web API ", Termsofser vice = "None", the page contact = new Contact {Name = "Linyongjie", Email = "", Url = "https://docs.microsof T.com/zh-cn/aspnet/core/"},58 License = new License {Name =" swagger official website ", URL =" http://swagger.io/" }59}); var basepath = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Def Ault. Application.applicationbasepath; Gets the root path of the application to the options.  Includexmlcomments (BasePath + "\\dotNetCore_Test1.xml"); is the full path of the XML comment file that needs to be set);}67//This method gets called by the Runti Me. Use this method to configure the HTTP request pipeline69 public void Configure (Iapplicationbuilder app, Ihostingen Vironment env, Iloggerfactory loggerfactory) {loggerfactory.addconsole (Configuration.getsection (" Loggi(ng ")); Loggerfactory.adddebug (); Useapplicationinsightsrequesttelemetry (), the app. Useapplicationinsightsexceptiontelemetry (); Usemvc (); Useswagger (); Enables middleware services to generate swagger as the JSON endpoint for the "app."  Useswaggerui (); Make middleware services Swagger-ui assets (HTML, JavaScript, CSS, etc.) 84 85}86}87}

11. Create a new user model for testing:

1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel.DataAnnotations; 4 using System.Linq; 5 using System.Threading.Tasks; 6  7 Namespace Dotnetcore_test1.models 8 {9//<summary>11//     User model///     </summary >13 public class User14 {from//<summary>18///         Age         </summary>// Public         int Age {set; get;} /  //<summary>23////</SUMMARY>25 [Required]//This configuration can be constrained (Swagger) The parameter value passed in cannot be empty         . public string Name {get; set;} *//<SUMMARY>30///         </summary>32 public         string Sex {get; set;}     }34}

12. Added XML Comment Controller example:

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading.Tasks; 5 using MICROSOFT.ASPNETCORE.MVC; 6 7 Namespace Dotnetcore_test1.controllers 8 {9//<summary>10//test swagger XML comments///</summ ary>12 [Route ("Api/[controller]")]13 public class Valuescontroller:controller14 {//<summa RY&GT;16////Get an array of information for//</summary>18//<returns></returns>19 [Http Get]20 public ienumerable<string> Get () {return new string[] {"value1", "value2"} }24///&LT;SUMMARY&GT;26///&LT;/SUMMARY&GT;28///<par         AM name= "id" > Primary key uniquely identifies </param>29//<returns> Returns a value </returns>30 [HttpGet ("{ID}")]31         public string Get (int id) + {"value";}35//<summary>37 /Add a user///</summary>39//&LT;REMARKS&GT;40////POST/USER42         {//"Age": "Ages", "///" name ":" title ","/"" Sex ":" Gender 46 }47///</remarks>49//<param name= "item" JSON object </param>5         0//<returns> Returns an object </returns>51//<response code= "201" > returns the newly created project </response>52 <response code= ">" If Item is null</response>53 [httppost]54 [Producesresponsetype (Ty         Peof (DotNetCore_Test1.Models.User), 201)]55 [Producesresponsetype (typeof (DotNetCore_Test1.Models.User), 400)]56             [httppost]57 Public Iactionresult Post ([frombody]dotnetcore_test1.models.user Item) 58 {59 if (item = = NULL) badrequest ();}63 return Ok (item); 6  4}65 66 67 68       ///&LT;SUMMARY&GT;70///Delete one object///</summary>72//<remarks>73         You can write a detailed note here.//</remarks>75//<param name= "id" > PRIMARY key ID identification </param>76 [Httpdelete ("{ID}")]77 public void Delete (int id) 78 {79}80}81}

13  http://localhost:<random_port>/swagger/ui  . Documents generated by Access to view swagger auto-generated documents (< random_port> 表示IIS Express随机分配的端口号,我测试的demo分配的端口号是:51109,所以我这里查看Swagger生成的文档地址是http://localhost:51109/swagger/ui/index.html#/Values ) such as:

13.1.

13.2

13.3

13.4

Configure Swagger to use the generated XML file

Documentation for automatic generation of ASP. NET core Web API using Swagger, online Help test document (ASP. NET core Web API automatically generate documents)

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.