ASP.NET Core Web API used Swagger


This section navigation

  • Swagger Introduction
  • Use of swagger in ASP.NET CORE

  In software development, testing and management API is an important and challenging work. Before my article "R & D team, please mind your API documentation" also devoted by the document management tools to ensure consistency API documentation and code, so more conducive to team collaboration.

  In the past we always manage our API documentation through a third party platform tools, such as eolinker . In testing, we will rely fiddler, such tools PostMan.

  Swagger both the API documentation and test management functionality, and ensure the consistency of code and documentation. It provides RESTfulAPI achieved without any logical representation of the UI. It allows users to understand the functions and services in the absence of any code to access the situation, and to reduce the time to create a service document.

1 Swagger Introduction

  Swagger both the API documentation and test management functionality, and ensure the consistency of code and documentation. It provides RESTfulAPI achieved without any logical representation of the UI. It allows users to understand the functions and services in the absence of any code to access the situation, and to reduce the time to create a service document.

  swagger swagger use tool to generate a document management interface based on our written service code generation swagger.json file. This document describes the functions of the service, that is how much support service method, and provide information about the method parameters. Using this file, SwaggerUI generate client code. Here is an example swagger.json file.

{
    "swagger": "2.0",
    "info": {
        "version": "1.0",
        "title": "My Demo API"
    },
    "paths": {
        "/api/Values": {
            "get": {
                "tags": ["Values"],
                "summary": "Get values",
                "operationId": "Get",
                "consumes": [],
                "produces": ["text/plain", "application/json", "text/json"],
                "parameters": [],
                "responses": {
                    "200": {
                        "description": "Success",
                        "schema": {
                            "uniqueItems": false,
                            "type": "array",
                            "items": {
                                "type": "string"
                            }
                        }
                    }
                }
            },
            "post": {
                "tags": ["Values"],
                "operationId": "Post",
                "consumes": ["application/json-patch+json", "application/json", "text/json", "application/*+json"],
                "produces": [],
                "parameters": [{
                    "name": "value",
                    "in": "body",
                    "required": false,
                    "schema": {
                        "type": "string"
                    }
                }],
                "responses": {
                    "200": {
                        "description": "Success"
                    }
                }
            }
        }
    },
    "definitions": {}
}

  In APS.NET Core Web API, we can use Swashbuckle.AspNetCore and NSwag two packages to achieve Swagger, and both are open source on github. In addition, nswag also provides a typescript client code generation method and an API service code.

1.2 TPL

  Task Parallel Library ( TPL ) is a set of common types and API System.Threading and System.Threading.Tasks namespace.

  TPL dynamically extend the degree of concurrency, with the most effective use of all available processors. By using TPL, you can maximize the performance of the code, while focusing on the business of your code implementation.

  From the beginning .NET Framework 4, TPL is the preferred way to write multithreaded and parallel code.

2 Use of swagger in ASP.NET CORE

  Here to Swashbuckle.AspNetCore to achieve.

  Here are the steps to configure Swagger in ASP.net Core Web API in:

1. Install Swashbuckle.AspNetCore

PM> Install-Package Swashbuckle.AspNetCore

2. Configure swagger middleware

  To swagger middle added to the request pipeline, the need to add swaggergen method configureService method startup class. Here, we can define one or more swagger XML documents.

Startup.cs

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1.0", new Info { Title = "My Demo API", Version = "1.0" });
                c.IncludeXmlComments(System.IO.Path.Combine(System.AppContext.BaseDirectory, "ZhiKeCore.API.xml"));
            });
        }

  To enable this middleware, we also need to call useswagger methods configure method startup class. Here, we also need to configure swagerendpoint to generate UI. useswagegrui add a static file middleware to load swager.json file.

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1.0/swagger.json", "My Demo API (V 1.0)");
            });
        }

  These are the basic steps to configure swagger, and if we want to use Visual Studio to start Swagger in a development environment, need to do a little set. Select items - property -Debug , modify the browser start (Launch Browser) value of swagger.

scenes to be used

  When we started the program, you can see the following interface:

scenes to be used

  As we see here, its HTTP verb to use for each different color codes. When we click on any method of operation, it will ask for more information parameter, when we click the "very" button, it sends a request to the Web API.

  In testing our WebAPI, Swagger require minimal configuration is required.

  So, if we want to display on the UI code comments should be how to do it?

  In .NET Core, we can set the "XML document file" attribute in the "Build" tab of the Project Properties window to get XML comments.

scenes to be used

  By default, Swagger UI does not display the document. We need to pass the path contains exmlcomments.

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
       // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1.0", new Info { Title = "My Demo API", Version = "1.0" });
                c.IncludeXmlComments(System.IO.Path.Combine(System.AppContext.BaseDirectory, "ZhiKeCore.API.xml"));
            });
        }

scenes to be used

reference

Attention
  please pay attention to micro-channel public number Chi Square off .

scenes to be used

Guess you like

Origin www.cnblogs.com/lucky_hu/p/11130209.html