ASP. NET core WebApi using Swagger build help page

Source: Internet
Author: User

Recently our team has been working on. NET core transformation, Web development toward the technology architecture of the front-end separation, we mainly use the ASP. Webapi to develop, start every debugging and communication with front-end people there is this inefficient problem, When I looked at the official Microsoft ASP. NET core document, I found the swagger this good thing. The technology is then introduced into the actual project. Our developers have greatly simplified the process of testing their own APIs, and the front-end staff can test their own front-end code based on the swagger help pages we provide, greatly improving the efficiency of the front-end development. Next I'll take my own real-life online project to explain how to introduce swagger in ASP. NET Core Webapi. (You can also refer to Microsoft Official documentation: Https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swagger)

first, the introduction of swagger NuGet Package

Right-click on the Wepapi project's dependencies and click Manage NuGet packages, such as:

In the Open NuGet Package Program management interface, enter: Swashbuckle.aspnetcore The package currently has a version of 1.0.0, click Install.

After installation, you need to configure it in the Startup.cs file in your project.

Second, the configuration swagger

Open the Startup.cs file, and in the Configureservices method, add the following code:

Services. Addswaggergen (c ={C.swaggerdoc ("v1",NewInfo {Version="v1", Title="Twbusmanagement Interface Documentation", Description="RESTful API for Twbusmanagement", Termsofservice="None", Contact=NewContact {Name ="Alvin_su", Email ="[email protected]", URL ="" }                }); //Set The comments path for the swagger JSON and UI.                varBasePath =PlatformServices.Default.Application.ApplicationBasePath; varXmlpath = Path.Combine (BasePath,"Twbusapi.xml");              C.includexmlcomments (Xmlpath); //c.operationfilter//Add httpheader parameter});

Note the last three lines of the previous code, which is the generated address and file name of our API description document XML, need to be configured in the properties of the project. Such as:

In addition, suppress the warning, add 1591 code, you can filter out some of the class name does not write comments alarm information.

Finally, in the Configure method, add the following code, note that the following code must be added to the app. USEMVC () Front:

// Enable middleware to serve generated Swagger as a JSON endpoint.             app. Useswagger ();             // Enable Middleware to serve Swagger-ui (HTML, JS, CSS etc), specifying the swagger JSON endpoint.            App. Useswaggerui (c + =            {                c.swaggerendpoint ("/swagger/v1/swagger.json  ""twbusmanagement API V1");                C.showrequestheaders ();            });

After the above configuration, you can use the swagger generated help page, after running the project, in the browser address suffix/swagger can jump to the help page:

Of course, our developers do not want to manually enter an address to jump to the help page each time they develop the project, which is too cumbersome. We can jump with Visual Studio, such as:

Open the Launchsettings.json file and set the startup path of the WEBAPI project to swagger. This will automatically jump to the Swagger help page for each debug run project

third, some advanced usage of swagger

Swagger is very powerful, not just some help page information, but also to debug the API. This allows for WEBAPI debugging without the use of third-party tools such as: Postman. Swagger is configured, you can also enter some HTTP header information, such as permission authentication information. The following specific configurations are explained below.

First we need to create a new class httpheaderoperation that inherits the Ioperationfilter interface. The interface needs to introduce a namespace: Swashbuckle.AspNetCore.SwaggerGen, implementing the interface method the apply code is as follows:

  Public classHttpheaderoperation:ioperationfilter { Public voidApply (Operation operation, Operationfiltercontext context) {if(Operation. Parameters = =NULL) {operation. Parameters=NewList<iparameter>(); }            varActionattrs =context.            Apidescription.actionattributes (); varIsauthorized= Actionattrs.any (A = a.gettype () = =typeof(Authorizeattribute)); if(IsAuthorized = =false)//provide action without permission attribute tag, check if controller has            {                varcontrollerattrs=context.                Apidescription.controllerattributes (); IsAuthorized= Controllerattrs.any (A = a.gettype () = =typeof(Authorizeattribute)); }            varIsallowanonymous = Actionattrs.any (a = a.gettype () = =typeof(Allowanonymousattribute)); if(isauthorized && isallowanonymous = =false) {operation. Parameters.Add (NewNonbodyparameter () {Name="Authorization",//adding Authorization Header parametersin ="Header", Type="string", Required=false                }); }        }    }

Then in the Startup.cs configureservices method, find the previous Addswaggergen code snippet, and at the end add the following code:

C.operationfilter
Services. Addswaggergen (c ={C.swaggerdoc ("v1",NewInfo {Version="v1", Title="Twbusmanagement Interface Documentation", Description="RESTful API for Twbusmanagement", Termsofservice="None", Contact=NewContact {Name ="Alvin_su", Email ="[email protected]", URL ="" }                }); //Set The comments path for the swagger JSON and UI.                varBasePath =PlatformServices.Default.Application.ApplicationBasePath; varXmlpath = Path.Combine (BasePath,"Twbusapi.xml");                C.includexmlcomments (Xmlpath); C.operationfilter<HttpHeaderOperation> ();//Add httpheader parameter});

This allows us to enter the Authorization header parameters after we allow the WEBAPI project. Such as:

For more information on swagger usage, refer to Https://github.com/domaindrivendev/Swashbuckle.AspNetCore and Microsoft documentation: https://docs.microsoft.com/ Zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swagger

ASP. NET core WebApi using Swagger build help page

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.