首页 > 技术文章 > .NetCore学习笔记:六、Swagger API接口文档工具

letnet 2020-07-29 17:05 原文

Swagger一个优秀的Api接口文档生成工具。Swagger可以可以动态生成Api接口文档,有效的降低前后端人员关于Api接口的沟通成本,促进项目高效开发。

1、使用NuGet安装最新的包:Swashbuckle.AspNetCore。

 2、编辑项目文件(NetCoreTemplate.Web.csproj),配置Xml文档生成目录。

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DocumentationFile>bin\Debug\netcoreapp3.1\NetCoreTemplate.Web.xml</DocumentationFile>
    <OutputPath>bin\Debug\netcoreapp3.1\</OutputPath>
  </PropertyGroup>
  
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <DocumentationFile>bin\Release\netcoreapp3.1\NetCoreTemplate.Web.xml</DocumentationFile>
    <OutputPath>bin\Release\netcoreapp3.1\</OutputPath>
  </PropertyGroup>

3、在项目中注册Swagger,添加一个文档信息和导入Xml文件信息。

// 注册Swagger服务
services.AddSwaggerGen(c =>
{
    // 添加文档信息
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "NetCoreTemplate Api", Version = "v1" });

    //导入XML文件信息
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
});

4、添加Swagger中间件和Page UI。

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "NetCoreTemplate V1");
});

这样配置就完成了,启动程序检验一下成果。

 

 

源码地址:https://github.com/letnet/NetCoreDemo

 

推荐阅读