.NET Core WEB API使用Swagger生成在線接口文檔
阿新 • • 發佈:2019-04-28
called bin eth abstract 程序 lin this new code
1項目引用Swashbuckle.AspNetCore程序集和Microsoft.Extensions.PlatformAbstractions程序集
右擊項目打開"管理NuGet程序包...",選擇Swashbuckle.AspNetCore進行安裝,如下圖所示:
選擇選擇Microsoft.Extensions.PlatformAbstractions進行安裝,如下圖所示:
2.在工程中配置Swagger
在Startup.cs類中的ConfigureServices中添加如下代碼:
// 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(options => { options.SwaggerDoc("v1", new Info { Version= "v1", Title = "Swagger示例 API" }); //Determine base path for the application. var basePath = PlatformServices.Default.Application.ApplicationBasePath; }); }
在Configure方法中添加如下代碼:
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(); //添加Swagger引用 app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger示例API V1"); }); }
3.Swagger在線接口文檔效果
工程運行後,在服務地址的端口號後面輸入swagger/index.html,在線文檔的效果就出來了,如下圖所示:
4.讓方法和字段顯示文字註釋
首先右擊項目,選擇“屬性”,讓項目輸出註釋xml文檔,如下圖所示:
在ConfigureServices方法中添加如下代碼:
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { Version = "v1", Title = "Swagger示例 API" }); //顯示文檔註釋 var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "SwaggerTest.xml"); options.IncludeXmlComments(xmlPath); }); }
給相應的接口方法和實體字段添加註釋後,啟動項目效果如下所示:
5.把Swagger文檔設置為項目的啟始頁
打開工程的launchSettings.json配置文件,把"launchUrl": 的地址修改為"swagger/index.html",如下圖所示:
.NET Core WEB API使用Swagger生成在線接口文檔