ASP.NET Core 3.1系列(12)——使用Swagger构建Web API文档

32 篇文章 42 订阅

1、前言

在前后端分离的开发模式下,相信无论是前端还是后端开发,都或多或少地被接口文档折磨过。前端经常抱怨后端给的接口文档与实际情况不一致,后端又觉得编写及维护接口文档会耗费不少精力,经常来不及更新。因此,随着时间推移和版本迭代,接口文档往往很容易就跟不上代码了。这时候我们就需要使用Swagger来帮助我们自动构建API文档。Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务。下面开始介绍如何在ASP.NET Core中使用它。

2、配置Swagger

2.1、引入Swagger组件

使用NuGet引入Swashbuckle.AspNetCore组件,版本选择最新的即可,如下图所示:

Swashbuckle.AspNetCore

在这里插入图片描述

2.2、添加Swagger服务

Startup.cs文件中添加对应的Swagger服务,代码如下所示:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;

namespace App
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            // 添加Swagger
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo 
                {
                    Title = "API文档",
                    Version = "v1",
                    Description = "ASP.NET Core API接口说明文档"
                });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // 添加Swagger有关中间件
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "API文档.v1");
            });

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

2.3、修改启动URL

在之前的博客中我们介绍过,launchSettings.json文件中的launchUrl属性规定了程序启动后的初始URL,现在需要将其修改为swagger,代码如下:

{
    "$schema": "http://json.schemastore.org/launchsettings.json",
    "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
            "applicationUrl": "http://localhost:18394",
            "sslPort": 44326
        }
    },
    "profiles": {
        "IIS Express": {
            "commandName": "IISExpress",
            "launchBrowser": true,
            "launchUrl": "swagger",
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            }
        },
        "App": {
            "commandName": "Project",
            "launchBrowser": true,
            "launchUrl": "swagger",
            "applicationUrl": "https://localhost:5001;http://localhost:5000",
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            }
        }
    }
}

2.4、运行Swagger

创建一个HomeController,然后添加一些方法,代码如下:

using Microsoft.AspNetCore.Mvc;

namespace App.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        /// <summary>
        /// 获取字符串
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<string> Get()
        {
            return "Hello World!";
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<string> Post([FromForm] string name)
        {
            return $"姓名:{name}";
        }
    }
}

运行程序,Swagger界面如下图所示:
在这里插入图片描述

现在可以测试一下GetPost方法,如下图所示:
在这里插入图片描述
在这里插入图片描述
到此为止,一个基本的Swagger界面就配置好了。

3、添加方法注释

HomeController中,我们给GetPost方法添加了相应的注释,如下图所示:
在这里插入图片描述
Swagger却并没有将这些注释显示出来,如下图所示:
在这里插入图片描述
如果将这样的Swagger界面交给前端人员查看,他们可能无法得知这些方法的具体作用和含义,因此我们需要让Swagger把每个方法的注释都显示出来。打开Startup.cs文件,添加如下代码:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using System;
using System.IO;

namespace App
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            // 添加Swagger
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo 
                {
                    Title = "API文档",
                    Version = "v1",
                    Description = "ASP.NET Core API接口说明文档"
                });
                
                // 添加注释
                var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                var xmlFile = AppDomain.CurrentDomain.FriendlyName + ".xml";
                var xmlPath = Path.Combine(baseDirectory, xmlFile);
                options.IncludeXmlComments(xmlPath);
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // 添加Swagger有关中间件
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "API文档.v1");
            });

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

然后打开项目属性界面,填写输出路径并勾选XML文档文件即可,如下图所示:
在这里插入图片描述
运行程序,发现Swagger已经能够显示每个方法的注释,如下图所示:
在这里插入图片描述

4、忽略Swagger注释警告

上面已经实现了Swagger显示方法注释的功能,但也有些美中不足,那就是在勾选XML文档文件之后会强制让你把所有的注释都添上,如下图所示,Visual Studio 2019给出了缺少注释的1591警告。
在这里插入图片描述
解决这个问题的方法有两个。一个是把注释全部加上,但如果工程规模较大,这可能需要花很长时间去添加注释信息。二是忽略1591警告,具体做法是:打开项目属性,在取消显示警告处添加;1591即可。
在这里插入图片描述
可以发现,警告信息和波浪线已经全部消失,如下图所示:
在这里插入图片描述

5、结语

本文主要介绍了Swagger的相关用法,对于前后端分离的开发模式来说,利用Swagger生成一份清晰明了的接口开发文档具有重要意义,它不仅能够免去传统Web API调试时的一些繁琐工序,而且还可以保证接口文档能够及时更新、减少前后端开发人员互相甩锅的情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值