Description
Swagger is a webapi online annotation, debugging plug-in, in the past we mainly by hand writing Webapi interface interactive document for front-end developers or external developers,
Official address: https://swagger.io/.
But in actual work, often the document work is often behind the actual environment, resulting in inconsistent documentation and actual interface, front and back developers miserable.
The advent of swagger frees up the hassle of interface documentation and improves the productivity of front-end developers, so-called "工欲善其事, its prerequisite". Now let's
Learn how to implement swagger under. NET Core 2.1.
1. NuGet Install dependency Package
First NuGet installation Swashbuckle.aspnetcore
Open the NuGet Console (Package management Console) and type the following command
Install-package Swashbuckle.aspnetcore
2. Add Swagger Middleware
Public IServiceProvider configureservices (iservicecollection services) {services. configure<cookiepolicyoptions> (Options + =//This lambda determines whether user cons ENT for non-essential cookies are needed for a given request. Options. checkconsentneeded = Context = true; Options. Minimumsamesitepolicy = Samesitemode.none; }); Services. Addmvc (). Addjsonoptions (Options + =//Ignore circular references options.) serializersettings.referenceloophandling = Referenceloophandling.ignore; Key options that do not use hump style. Serializersettings.contractresolver = new Defaultcontractresolver (); }) . Setcompatibilityversion (Compatibilityversion.version_2_1); Register the Swagger generator, defining 1 or more Swagger documents services. Addswaggergen (c + = {C.swaggerdoc ("v1", new Info {Title = "My API", Version = "V1"}); }); return REGISTERAUTOFAC (services);//Register AUTOFAC}
Referencing Swashbuckle.AspNetCore.Swagger, and enabling middleware
1 Public voidConfigure (Iapplicationbuilder app, ihostingenvironment env)2 {3 if(env. Isdevelopment ())4 {5 app. Usedeveloperexceptionpage ();6 }7 //Enable middleware to serve generated Swagger as a JSON endpoint.8 app. Useswagger ();9 //Enable Middleware to serve Swagger-ui (HTML, JS, CSS, etc),Ten //specifying the Swagger JSON endpoint. OneApp. Useswaggerui (c = A { -C.swaggerendpoint ("/swagger/v1/swagger.json","My API V1"); - }); the app. Usevisitlogger (); - app. Usemvc (); -}
3. Configuring WEBAPI Project Properties
1. Double-click the Launchsettings.json under Properties to update Launchurl to swagger
F5 results are as follows:
. NetCore2.1 Webapi added Swagger plugin