关于.net:如何在-ASPNet-Core-中使用-Swagger

6次阅读

共计 3728 个字符,预计需要花费 10 分钟才能阅读完成。

大家在开发完 webapi 后,常常为了不便接口单方对接,须要将 webapi 接口文档化,那有没有什么快捷可交互的文档呢?能够利用快捷工具 Swagger,它的可视化 UI 可轻松助你 API 文档化的同时还不便测试 API。

Swashbuckle 就是一个用于生成 Swagger 文档的开源工具包,这篇文章将会探讨如何利用 Swashbuckle 来为你的 Restful API 生成可交互的文档。

装置 Swagger 中间件

要想利用 Swagger 文档化,须要 nuget 援用 Swashbuckle.AspNetCore 包,还能够通过 Visual Studio 2019 的 NuGet package manager 可视化界面装置 或者 通过 NuGet package manager 命令行工具输出以下命令:


dotnet add package Swashbuckle.AspNetCore

配置 Swagger 中间件

为了配置 Swagger,在 Startup.ConfigureServices 办法中增加如下代码,留神上面的 AddSwaggerGen 办法是用于给 API 文档 增加一些元数据。


            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "Swagger Demo",
                    Description = "Swagger Demo for ValuesController",
                    TermsOfService = "None",
                    Contact = new Contact() { Name = "Joydip Kanjilal",
                    Email = "joydipkanjilal@yahoo.com",
                    Url = "www.google.com" }
                });
            });

接下来就要启动 Swagger 了,在 Startup.Configure 办法下增加如下代码:


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

为了完整性,上面是 Startup 中的所有代码清单。


using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;
namespace IDGSwaggerDemo
{
    public class Startup
    {public Startup(IConfiguration configuration)
        {Configuration = configuration;}
        public IConfiguration Configuration {get;}
        public void ConfigureServices(IServiceCollection services)
        {services.AddMvc().SetCompatibilityVersion
            (CompatibilityVersion.Version_2_2);   
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "Swagger Demo",
                    Description = "Swagger Demo for ValuesController",
                    TermsOfService = "None",
                    Contact = new Contact() { Name = "Joydip Kanjilal",
                    Email = "joydipkanjilal@yahoo.com",
                    Url = "www.google.com"
                }
                });
            });
        }
        public void Configure(IApplicationBuilder app,
       IHostingEnvironment env)
        {if (env.IsDevelopment())
            {app.UseDeveloperExceptionPage();
            }
            app.UseMvc();
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
            });
        }
    }
}

浏览 Swagger UI

当初咱们运行一下应用程序来浏览一下 Swagger UI 地址,能够看到 UI 界面如下图所示,图中不同的 Http 申请应用了不同的色彩进行标识,你甚至能够在 UI 上间接测试不同的 api 接口。

在 Action 办法上创立 xml 注解

到目前为止一切顺利,在方才生成的 swagger 文档中,并没有看到 5 个 api 接口的任何注解,这就不优雅了,如果想要在 swagger 文档上减少 xml 注解,简略粗犷的做法能够间接在 Controller.Action 顶部写上注解信息。

接下来在 ValuesController 下的每一个 Action 上都加上注解,上面就是批改后的 ValueController


    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        /// <summary>
        /// Get action method without any argument
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {return new string[] {"value1", "value2"};
        }

        /// <summary>
        /// Get action method that accepts an integer as an argument
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {return "value";}

        /// <summary>
        /// Post action method to add data
        /// </summary>
        /// <param name="value"></param>
        [HttpPost]
        public void Post([FromBody] string value)
        { }

        /// <summary>
        /// Put action method to modify data
        /// </summary>
        /// <param name="id"></param>
        /// <param name="value"></param>
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        { }

        /// <summary>
        /// Delete action method
        /// </summary>
        /// <param name="id"></param>
        [HttpDelete("{id}")]
        public void Delete(int id)
        {}}

关上 xml 注解

值得注意的是:Swagger 默认并不会显示 XML 注解,须要手工关上它,那怎么做呢?右键 Project,抉择 Properties 后切换到 Build 页面,而后选中 XML documentation file 项 并且指定好 xml 生成的地位,参考如下:

接下来还要在 ConfigureServices 办法下将生成 xml 的门路配置到 swagger 中,如下代码所示:


c.IncludeXmlComments(@"D:\Projects\IDG\IDGSwaggerDemo\IDGSwaggerDemo\IDGSwaggerDemo.xml");

这就是关上 Swagger 中的 xml 注解 所需的所有事件。

指定启动 url 到 Swagger UI

要想将启动我的项目的 url 指到 SwaggerUI,右键 Project 并抉择 Properties,在 Debug 的 Lanuch browser 上指定 swagger 即可,如下图所示:

再次运行程序能够发现默认页就是 Swagger URL 了,如下图所示:

从图中能够看到,5 个 API 办法前面都有相应的 xml 注解了。

Swashbuckle 是一个十分好的工具,能够简略粗犷的给 API 接口生成文档,从文中也能够看出 Swashbuckle 的配置非常简单,Swagger 还有一些更高级的性能,比方通过 CSS 来定制 Swagger UI,还能够依据 API 的版本生成不同的 Swagger 文档,后续的文章还会跟大家介绍更多高级的性能。

译文链接:https://www.infoworld.com/art…

更多高质量干货:参见我的 GitHub: csharptranslate

正文完
 0