前言:我们开发了很多的接口后,为了方便调用人员使用,需要给出接口地址,参数和解释说明,可能还需要示例。 那么swagger这个开源项目,已经给我们提供好了一整套的解决方案:
本博客参考文档:
什么是 Swagger/OpenAPI?
Swagger 是一个与语言无关的规范,用于描述 REST API。 Swagger 项目已捐赠给 OpenAPI 计划,现在它被称为开放 API。 这两个名称可互换使用,但 OpenAPI 是首选。 它允许计算机和人员了解服务的功能,而无需直接访问实现(源代码、网络访问、文档)。 其中一个目标是尽量减少连接取消关联的服务所需的工作量。 另一个目标是减少准确记录服务所需的时间。(说明参考微软官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swagger?view=aspnetcore-3.0)
快速添加webapi项目对swagger的支持:
1-添加程序包引用:Swashbuckle.AspNetCore -Version 5.0.0-rc4 (该版本目前属于预览版,需要勾选预览版才可以看到)
2-添加并配置 Swagger 中间件:
using Microsoft.OpenApi.Models; public void ConfigureServices(IServiceCollection services) { // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); // include document file c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(Startup).Assembly.GetName().Name}.xml"), true); }); services.AddControllers(); }
这里,需要添加对项目xml文件的引用,默认启用根目录下的项目文件名的xml文件,项目xml文件生成配置如下:
为了兼容发布版本,咱们设置了输出路径为空,xml名称改为:项目名.xml
3-在 Startup.Configure
方法中,启用中间件为生成的 JSON 文档和 Swagger UI 提供服务:
public void Configure(IApplicationBuilder app) { // 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.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
4-结束,查看效果:
启动应用,并导航到: http://localhost:<port>/swagger/v1/swagger.json
。 生成的描述终结点的文档显示在 Swagger 规范 (swagger.json) 中。
可在 http://localhost:<port>/swagger
找到 Swagger UI。 通过 Swagger UI 浏览 API
5-走过的坑1:官网文档前半部分并没有让添加xml文件的代码。后面有涉及,不过还是感觉有点乱,本博客已加上!
走过的坑2:常见异常:Ambiguous HTTP method for action - PaymentAccountAPI.Controllers.PayAccountController.GetTransactions (PaymentAccountAPI). Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0
该异常是因为控制器方法,缺少方法类型的标记,[HttpGet]、[HttpPost],如下图:
参考解决方案文档:Ambiguous HTTP method Actions require an explicit HttpMethod binding for Swagger 2.0
走过的坑3:缺少xml项目文件异常_500错误: 项目部署到IIS后,不会自动把xml文件带过去,需要我们收到复制过去,在运行查看效果。
把项目xml文件放入后,再试(需要重启IIS项目),效果正常: