.net core 使用swagger自动生成接口文档

时间:2023-03-09 05:47:16
.net core 使用swagger自动生成接口文档

 前言

swagger是一个api文档自动生动工具,还集成了在线调试. 可以为项目自动生成接口文档, 非常的方便快捷

Swashbuckle.AspNetCore 是一个开源项目,用于生成 ASP.NET Core Web API 的 Swagger 文档. 本文采用这个!

一. 利用nuget添加引用 swashbuckle.AspNetCore

注意.net core 3.0需要引用 swashbuckle.AspNetCore 5.0 以上, 由于目前(2019/12/12)nuget 上最新的是4.0.1 所以要手动添加

地址 https://www.nuget.org/packages/Swashbuckle.AspNetCore

.net core 使用swagger自动生成接口文档

二. 在 Startup.cs 里面注册服务,添加中间件

添加引用

      using Swashbuckle.AspNetCore.Swagger;

注册服务

        public void ConfigureServices(IServiceCollection services)
{
//注册Swagger生成器,定义一个和多个Swagger 文档
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });//设置版本号,标题
var xmlPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "SwaggerApi.xml");// 为 Swagger JSON and UI设置xml文档注释路径
c.IncludeXmlComments(xmlPath);//只有设置了xmlm文档的路径生成的文档才会有注释
});
           services.AddMvc();
        }

注意..net core 3.0这里有个改动, 使用这个代码

            //注册Swagger生成器,定义一个和多个Swagger 文档
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My API", Version = "v1" });// .net core 3.0
//c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });//设置版本号,标题 .net core 2.0
var xmlPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "SwaggerApi.xml");// 为 Swagger JSON and UI设置xml文档注释路径
c.IncludeXmlComments(xmlPath);//只有设置了xmlm文档的路径生成的文档才会有注释
});

添加中间件

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();
//启用中间件服务对swagger-ui,指定Swagger JSON终结点
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseMvc();
}

三. 修改项目属性

1. 在生成的输入里面勾选 XML文档文件, 并将文件名更改为注册服务的定义的文件名,地址建议改为相对地址

.net core 使用swagger自动生成接口文档

2. 可以选择隐藏1591的错误提示,不隐藏所有没有写注释的地方都会有警告

.net core 使用swagger自动生成接口文档

3. 如果有多个项目,需要在注册服务时新增一个xml文件路由,并在另一个项目里也修改项目属性

.net core 使用swagger自动生成接口文档

.net core 使用swagger自动生成接口文档

4. 修改生成的xml文件的属性,将"复制到输出目录"改为"始终复制"

.net core 使用swagger自动生成接口文档

 四. 写接口调试

1. 创建返回实体, 要想接口中自带注释说明,实体必须要写上注释

        /// <summary>
/// 返回实体
/// </summary>
public class TestResult
{
/// <summary>
/// 用户Id
/// </summary>
public string Id;
/// <summary>
/// 用户名称
/// </summary>
public string Name;
}

2. 写接口

需要注意action的路由,请求方式,返回类型,都要加上,否则会导致文档不全

.net core 使用swagger自动生成接口文档

        /// <summary>
/// 测试接口
/// </summary>
/// <param name="id">用户Id</param>
/// <returns></returns>
[Route("api/[controller]/[action]")]
[HttpGet]
[ProducesResponseType(typeof(TestResult), )]
public IActionResult Test(string id)
{
return Ok(new TestResult
{
Id = id,
Name = "Hello World"
});
}

五. 查看结果

https://localhost:xxxx/swagger/index.html

.net core 使用swagger自动生成接口文档

展开

.net core 使用swagger自动生成接口文档

六. 在线调试 点击 Try It Out

.net core 使用swagger自动生成接口文档

填写参数

.net core 使用swagger自动生成接口文档

结果

.net core 使用swagger自动生成接口文档

七. 添加头部参数

1. 新增OperationFilter的实现

public class SwaggerHeaderFilterr : IOperationFilter
{
/// <summary>
/// swagger新增头部参数
/// </summary>
/// <param name="operation"></param>
/// <param name="context"></param>
public void Apply(Operation operation, OperationFilterContext context)
{
var headers = new Dictionary<string, string> { { "appkey", "分配的AppKey" }, { "randomcode", "随机码" }, { "timestamp", "时间戳(秒数)" }, { "sign", "签名" } };
foreach (var item in headers)
{
operation.Parameters.Add(new NonBodyParameter()
{
Name = item.Key,
In = "header",//query header body path formData
Type = "string",
Description = item.Value,
Required = false //是否必选
});
}
} }

2. 在AddSwaggerGen中添加

OperationFilter<SwaggerHeaderFilterr>();

.net core 使用swagger自动生成接口文档

3. 查看结果

.net core 使用swagger自动生成接口文档

注:

1. 如何修改首页的路由

.net core 使用swagger自动生成接口文档

.net core 使用swagger自动生成接口文档