WebApi使用swagger ui自动生成接口文档

2023-02-28,,

之前就写到。最近正在使用webapi。这里介绍一个实用的东西swageer ui
现在开发都是前后端分开。我们这里是给前端提供api。有时候对于一个api的描述,并不想专门写一份文档。很浪费时间。
swagger ui就是一个能整合到项目中让api的注释能够生成到一个网页上。能简单测试和给前端看。
开怼吧。

Step.1 Nuget安装
打开你的Nuget console,Install-Package Swashbuckle(要选择哪个项目)

ps.其实第一步安装完了,你什么不用做。运行起来,网址进入/swagger/ui/index就能看到你的那些api了(不带注释),不过没达到我们的预期效果——将注释自动生成到文档上。so,继续往下看

Step.2 加上生成注释的代码
安装之后会在App_Start文件夹中多了SwaggerConfig.cs类,该类中的Register()方法会在应用程序启动的时候调用
里面好多注释,绿绿的,还是选择原谅他,删掉吧,删掉后就这剩下这些

 public static void Register()
{
  var thisAssembly = typeof(SwaggerConfig).Assembly;   GlobalConfiguration.Configuration
  .EnableSwagger(c =>
  {
    c.SingleApiVersion("v1", "WebApplication1");
  })
  .EnableSwaggerUi(c =>
  {   });
}

稍微改造一下,附加个注释xml上去

 public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "WebApplication1");
c.IncludeXmlComments(GetXmlCommentsPath());
})
.EnableSwaggerUi(c =>
{ });
}
private static string GetXmlCommentsPath()
{
return System.String.Format(@"{0}\bin\WebApplication1.XML", System.AppDomain.CurrentDomain.BaseDirectory);
}

Step.3 步骤2所必须的
启用生成xml文档,右击项目文件属性 bulid发布——Output输出(勾选XML文件)

其实swagger他就是依赖于build时生成的这个xml来自动生成注释上页面的

Step.4 完成啦,看看页面


当然,我的追求不止这些,我们来优化优化
首先,我比较喜欢将config都弄进WebApiConfig中就好,看起来比较清晰

 public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services // Web API routes
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
); config.RegistSwagger();//添加这个swagger的Regist
}
private static void RegistSwagger(this HttpConfiguration config)
{
config.EnableSwagger("docs/{apiVersion}/swagger", c =>
{
c.SingleApiVersion("v1", "WebApplication1");
c.IncludeXmlComments(GetXmlCommentsPath());
})
.EnableSwaggerUi(c=>
{ });
}
private static string GetXmlCommentsPath()
{
return $@"{AppDomain.CurrentDomain.RelativeSearchPath}\WebApplication1.XML";
}
}

这个swagger的路径也配一下吧,可以自定义一下

 private static void RegistSwagger(this HttpConfiguration config)
{
config.EnableSwagger("docs/{apiVersion}/swagger", c =>
{
c.SingleApiVersion("v1", "WebApplication1");
c.IncludeXmlComments(GetXmlCommentsPath());
})
.EnableSwaggerUi("apis/{*assetPath}");//原本进入的地址是/swagger/ui/index 这样就能换地址成/apis/index
}

这样,我们这基本的配置就可以了,实现预期的效果——自动生成接口文档
这里面的配置应该还很多,等我有空更新哈,先这样

WebApi使用swagger ui自动生成接口文档的相关教程结束。

《WebApi使用swagger ui自动生成接口文档.doc》

下载本文的Word格式文档,以方便收藏与打印。