1. 程式人生 > >DotnetCore之旅(2)---swagger的簡單使用

DotnetCore之旅(2)---swagger的簡單使用

ati ice span dds host end read uil soft

swagger

swagger用於可視化api,並可實現對api格式化說明以及測試。

使用swagger

首先通過nuget引入Swashbuckle.AspNetCore(切記不是swagger)

技術分享圖片

其次修改程序生成屬性,分別配置程序生成路徑和xml文檔生成路徑

技術分享圖片

第三部修改startup類

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Threading.Tasks;
 6 using
Microsoft.AspNetCore.Builder; 7 using Microsoft.AspNetCore.Hosting; 8 using Microsoft.AspNetCore.Mvc; 9 using Microsoft.Extensions.Configuration; 10 using Microsoft.Extensions.DependencyInjection; 11 using Microsoft.Extensions.Logging; 12 using Microsoft.Extensions.Options; 13 using Swashbuckle.AspNetCore.Swagger;
14 15 namespace NetCoreExample 16 { 17 public class Startup 18 { 19 public Startup(IConfiguration configuration) 20 { 21 Configuration = configuration; 22 } 23 24 public IConfiguration Configuration { get; } 25 26 // This method gets called by the runtime. Use this method to add services to the container.
27 public void ConfigureServices(IServiceCollection services) 28 { 29 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 30 //添加SwaggerGen,配置api說明xml文檔 31 services.AddSwaggerGen(p => 32 { 33 p.SwaggerDoc("v1", 34 new Info { Title = "NetCoreExampleAPI", Version = "v1" } 35 ); 36 string xmlPath = Path.Combine(AppContext.BaseDirectory, "NetCoreExample.xml"); //程序說明xml文檔路徑 37 p.IncludeXmlComments(xmlPath); 38 }); 39 } 40 41 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 42 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 43 { 44 if (env.IsDevelopment()) 45 { 46 app.UseDeveloperExceptionPage(); 47 } 48 app.UseMvc(); 49 50 51 //註冊swagger插件 52 app.UseSwagger(); 53 app.UseSwaggerUI(p => 54 { 55 p.SwaggerEndpoint("/swagger/v1/swagger.json", "NetCoreExampleAPI V1");//註意v1是與AddSwaggerGen中指定的名稱一致 56 }); 57 } 58 } 59 }

最後運行後訪問http://localhost:5000/swagger/index.html

技術分享圖片

附:當然也可以配置多個api說明文檔,不一定是程序本身的api說明。需確認xml文檔正確有效,即可配置。以上是針對項目本身進行簡單配置。如果需要其他的配置,請參照swagger官網

DotnetCore之旅(2)---swagger的簡單使用