前言:咱们开发了不少的接口后,为了方便调用人员使用,须要给出接口地址,参数和解释说明,可能还须要示例。 那么swagger这个开源项目,已经给咱们提供好了一整套的解决方案:web
本博客参考文档:json
Swashbuckle 和 ASP.NET Core 入门 api
什么是 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)app
快速添加webapi项目对swagger的支持:visual-studio
1-添加程序包引用:Swashbuckle.AspNetCore -Version 5.0.0-rc4 (该版本目前属于预览版,须要勾选预览版才能够看到)ui
2-添加并配置 Swagger 中间件:spa
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文件生成配置以下:.net
为了兼容发布版本,我们设置了输出路径为空,xml名称改成:项目名.xml code
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项目),效果正常: