Asp.Net Core Integration Swagger

  Work in a company have a lot of projects, interactions between projects often need to write API to implement, but the preparation of the document is a tedious and time-consuming work, and with the iteration of the API, always need to update the maintenance interface documentation very often forget or because the person is willing to create an alternate interface documentation is inconsistent with the code.

  In practice, some companies will be forced to code specifications, requirements and code must have the comment fields, methods, classes, interfaces, etc. naming convention. But many small companies do not exist, even according to the norms still need to write code to maintain a additional documents (word, Excel, markdown, etc.), used to call other systems or provide front-end and very time consuming.

  So is there any way it can quickly generate documents and follow the code of iterations change? The answer is with Swagger, Swagger tool can help generate and maintain complete API documentation work, ensure that the document up to date in the API development process.

  Swagger's official website mainly provides several open source tools: Swagger Codegen can generate server or client code for the API; page display so that the caller interfaces people can face the relevant interface on this page were access and do Swagger UI provides a visual UI Some simple request; Swagger editor similar markendown editor edit Swagger description file editor, which supports updating the effect of real-time preview editing description file; Swagger Inspector is an interface can be tested online version postman. Than do Swagger UI interface request in the inside, will return more information will save the actual request parameters and other data you request; Swagger Hub integrates various functions of all of the above items, you can project and version as a unit, you will the description file uploaded to Swagger Hub in. Specific to view the official website: https://swagger.io/ .

  Here we only show you how to integrate in Asp.net core Swagger.

  New .net core Api project 2.2 SWagger.Api, the first to use Swagger in asp.net core, we need to introduce Nuget package Swashbuckle.AspNetCore.

Install-Package Swashbuckle.AspNetCore

  The UserController new controller, and to achieve Get, Put, Post, Delete method, a method to specify specific properties and add the necessary annotations.

the using the System;
 the using the System.Collections.Generic;
 the using the System.Linq;
 the using System.Threading.Tasks;
 the using Microsoft.AspNetCore.Mvc; 

namespace Swagger.Api.Controllers 
{ 
    ///  <Summary> 
    /// user interface
     ///  </ Summary> 
    [the Route ( " API / [Controller] " )] 
    [ApiController] 
    public  class the UserController: the Controller 
    { 
        ///  <Summary> 
        /// Gets information about all users
         ///  </ Summary> 
        ///  < returns> All users</ Returns> 
        [HttpGet] 
        [the Route ( "" )]
         public IActionResult the Get () 
        { 
            return Json ( new new {Id = . 1 , the Name = " Jesen " , In Email = " [email protected] " }); 
        } 

        // /  <Summary> 
        /// Id user information acquired by the user
         ///  </ Summary> 
        ///  <Remarks> 
        /// ID value must pass
         ///  </ Remarks> 
        ///  <param name = "ID" > user Id </ param> 
        ///  <returns> User Information</returns>
        /// <response code="200">返回用户信息</response>
        /// <response code="400">如果id为空</response>  
        [HttpGet]
        [Route("{id}")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<IActionResult> Get(int? id)
        {
            if (id == null) return BadRequest();

            return Json(new { Id = id, Name = "Jesen " , In Email = " [email protected] " }); 
        } 

        ///  <Summary> 
        /// Add User
         ///  </ Summary> 
        ///  <param name =" User "> the User Object Json </ param> 
        ///  <= Response code "200 is"> returns the user information </ Response> 
        ///  <Response code = "400"> error </ Response>   
        [HttpPost] 
        [ProducesResponseType ( 200 is )] 
        [ProducesResponseType ( 400 ) ]
         public  the async the Task <IActionResult> Post([FromBody] User user)
        { 
            ReturnOK (User); 
        } 

        ///  <Summary> 
        /// change user
         ///  </ Summary> 
        ///  <param name = "User"> the User Object Json </ param> 
        ///  <Returns> </ Returns> 
        [HTTP PUT]
         public  the async the Task <IActionResult> of Put ([FromBody] the user user) 
        { 
            return Ok (user); 
        } 

        ///  <Summary> 
        /// remove user through a user Id
         ///  </ Summary> 
        // /  <param name = "ID"> user Id </ param> 
        ///  <Returns> </ Returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            return Ok();
        }
    }
}

  You can see the interface and we usually write about, do not need to do other work, integrated in the .net core in Swagger need to do is to inject it in the Startup and added the middleware.

public  void ConfigureServices (IServiceCollection Services) 
        { 
            // Register Swagger generator, and define a plurality of documents Swagger 
            services.AddSwaggerGen (C => 
            { 
                c.SwaggerDoc ( " V1 " , new new Info { 
                    the Title = " User Interface System " , 
                    Version = " v1 " , 
                    the Description = " user Interface External system " , 
                    termsOfService = " None ",
                    Contact = new Contact
                    {
                        Name = "Jesen",
                        Email = string.Empty,
                        Url = "http://www.cnblogs.com/jesen1315/"
                    },
                    License = new License
                    {
                        Name = "许可证名字",
                        Url = "http://www.cnblogs.com/jesen1315/ " 
                    } 
                }); 

                // the UI provided xml document annotation path and the JSON Swagger 
                var the basePath Path.GetDirectoryName = ( typeof (Program) .Assembly.Location); // Get application program directory (absolute, not the working directory, we suggest using this method to obtain the path) 
                var XMLPath = Path.Combine (basePath, " Swagger.Api.xml " ); 
                c.IncludeXmlComments (XMLPath); 
            }); 

            services.AddMvc () .SetCompatibilityVersion (CompatibilityVersion.Version_2_2); 
        }
 public  void the Configure (App IApplicationBuilder, IHostingEnvironment the env) 
        { 
            IF (env.IsDevelopment ()) 
            { 
                app.UseDeveloperExceptionPage (); 
            } 
            the else 
            { 
                // . HSTS of The default value IS On May 30 Days by You want to Change Production Scenarios for the this, See https://aka.ms/aspnetcore-hsts. 
                app.UseHsts (); 
            } 

            // enable middleware services Swagger generated as JSON endpoint 
            app.UseSwagger ();
             // enable middleware service swagger-ui, designated Swagger JSON endpoint 
            app.UseSwaggerUI (C =>  
            {
                c.SwaggerEndpoint ( "/swagger/v1/swagger.json", "Swagger.Api V1");
            });

            //app.UseHttpsRedirection();
            app.UseMvc();
        }

  So far, the project can access and run a simple debugging in your browser.

 

   Is not very simple, Swagger can also generate xml documents generated for the project in time

 

 

Guess you like

Origin www.cnblogs.com/jesen1315/p/11416322.html