swagger:API在线文档自动生成框架

时间:2022-02-17 00:35:31

传统的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" />

swagger:API在线文档自动生成框架

2、api项目属性

swagger:API在线文档自动生成框架

3、修改swaggernet.cs

swagger:API在线文档自动生成框架

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

swagger:API在线文档自动生成框架

文档:

官网:https://swagger.io

微软文档:https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/creating-api-help-pages

NetCore使用:https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio

博客资源:http://www.cnblogs.com/dotNETCoreSG/p/aspnetcore_02-09_web-api-help-pages-using-swagger.html