传统的API从开发测试开始我们经常借用类似Postman、fiddle等等去做接口测试等等工具;Swagger 为API的在线测试、在线文档提供了一个新的简便的解决方案;
NET 使用Swagger
1、引用包
<package id="Swagger.Net.UI" version="1.1.0" targetFramework="net45" />
<package id="Swashbuckle" version="5.6.0" targetFramework="net45" />
2、api项目属性
3、修改swaggernet.cs
SwaggerConfig.cs
取消注释:c.IncludeXmlComments(GetXmlCommentsPath());
增加
private static string GetXmlCommentsPath() { return string.Format("{0}/bin/OPracticeWebAPI.XML", System.AppDomain.CurrentDomain.BaseDirectory); }
http://localhost:56651/swagger
NET CORE 使用Swagger
NET使用:Swagger-Net
引用NuGet包:Swashbuckle.AspNetCore ;
包含如下部分:
Swashbuckle.AspNetCore.Swagger: 一些模型实体定义
Swashbuckle.AspNetCore.SwaggerGen: Swagger生成器
Swashbuckle.AspNetCore.SwaggerUI:Swagger UI工具
配置:startup.cs
注入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