传统的API从开发测试开始咱们常常借用相似Postman、fiddle等等去作接口测试等等工具;Swagger 为API的在线测试、在线文档提供了一个新的简便的解决方案;html
一、引用包web
二、api项目属性json
三、修改swaggernet.csapi
NET使用:Swagger-Netrestful
引用NuGet包:Swashbuckle.AspNetCore ;app
包含以下部分:dom
Swashbuckle.AspNetCore.Swagger: 一些模型实体定义
Swashbuckle.AspNetCore.SwaggerGen: Swagger生成器
Swashbuckle.AspNetCore.SwaggerUI:Swagger UI工具工具
配置:startup.csvisual-studio
注入swagger:测试
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Register the Swagger generator, defining one or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // 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", "My API V1"); }); app.UseMvc(); }
编译运行,下面两个网址:
API文档界面:http://localhost:<random_port>/swagger
API的restful说明json文件:http://localhost:<random_port>/swagger/v1/swagger.json
文档:
博客资源:http://www.cnblogs.com/dotNETCoreSG/p/aspnetcore_02-09_web-api-help-pages-using-swagger.html