对于开发人员来说,构建一个消费应用程序时去了解各种各样的 API 是一个巨大的挑战。
在你的 Web API 项目中使用 Swagger 的 .NET Core 封装 Swashbuckle 可以帮助你创建良好的文档和帮助页面。 Swashbuckle 可以通过修改 Startup.cs 作为一组 NuGet 包方便的加入项目。
Swashbuckle 是一个开源项目,为使用 ASP.NET Core MVC 构建的 Web APIs 生成 Swagger 文档。
Swagger 是一个机器可读的 RESTful API 表现层,它可以支持交互式文档、客户端 SDK 的生成和可被发现。

Swashbuckle 有两个核心的组件
Swashbuckle.SwaggerGen : 提供生成描述对象、方法、返回类型等的 JSON Swagger 文档的功能。
Swashbuckle.SwaggerUI : 是一个嵌入式版本的 Swagger UI 工具,使用 Swagger UI 强大的富文本表现形式来可定制化的来描述 Web API 的功能,并且包含内置的公共方法测试工具。

新建一个ASP.NET Core WebApi 项目,项目结构如下图所示:

使用NUget进行添加Swashbuckle

1、工具->NUget包管理器->程序包管理器控制台

2、在控制台输入: Install-Package Swashbuckle -Pre  按下回车键

3、安装Swashbuckle完成:

4、安装Swashbuckle完成后台项目的引用发生了变化:

5、在 project.json 中添加多了一项配置 "Swashbuckle": "6.0.0-beta902" :

7、启用 XML 注释, 在 Visual Studio 中右击项目并且选择 Properties 在 Output Settings 区域下面点击 XML Documentation file 。

9、在 project.json 中设置 “xmlDoc”: true 来启用 XML 注释。

10、在Startup.cs类的 ConfigureServices 方法中,允许中间件提供和服务生成 JSON 文档以及 SwaggerUI。Configure 方法中把 SwaggerGen 添加到 services 集合。配置 Swagger 使用生成的 XML 文件

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.Swagger.Model; namespace dotNetCore_Test1
{ public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
} public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration); services.AddMvc(); //services.AddLogging(); // 注入的实现ISwaggerProvider使用默认设置
services.AddSwaggerGen(); services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "测试ASP.NET Core WebAPI生成文档(文档说明)",
Description = "A simple example ASP.NET Core Web API",
TermsOfService = "None",
Contact = new Contact { Name = "linyongjie", Email = "", Url = "https://docs.microsoft.com/zh-cn/aspnet/core/" },
License = new License { Name = "Swagger官网", Url = "http://swagger.io/" }
}); var basePath = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath; // 获取到应用程序的根路径
options.IncludeXmlComments(basePath + "\\dotNetCore_Test1.xml"); //是需要设置 XML 注释文件的完整路径
}); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug(); app.UseApplicationInsightsRequestTelemetry(); app.UseApplicationInsightsExceptionTelemetry(); app.UseMvc(); app.UseSwagger(); //使中间件服务生成Swagger作为JSON端点 app.UseSwaggerUi(); //使中间件服务swagger-ui assets (HTML、javascript、CSS等等) }
}
}

11、新建一个User(用户)Model用于测试:

 using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks; namespace dotNetCore_Test1.Models
{ /// <summary>
/// 用户模型
/// </summary>
public class User
{ /// <summary>
/// 年龄
/// </summary>
public int Age { set; get; } /// <summary>
/// 名称
/// </summary>
[Required] //此配置可以约束(Swagger )传进来的参数值 不能为空
public string Name { get; set; } /// <summary>
/// 性别
/// </summary>
public string Sex { get; set; }
}
}

12、添加了XML注释控制器例子:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; namespace dotNetCore_Test1.Controllers
{
/// <summary>
/// 测试 Swagger的 XML 注释
/// </summary>
[Route("api/[controller]")]
public class ValuesController : Controller
{
/// <summary>
/// 获得一个数组信息
/// </summary>
/// <returns></returns>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
} /// <summary>
/// 根据id获取信息
/// </summary>
/// <param name="id">主键唯一标识</param>
/// <returns>返回一个值</returns>
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
} /// <summary>
/// 添加一个用户
/// </summary>
/// <remarks>
///
/// POST /User
/// {
/// "Age": "年龄",
/// "Name": "名称",
/// "Sex": "性别
/// }
///
/// </remarks>
/// <param name="item">用户的json对象</param>
/// <returns>返回一个对象</returns>
/// <response code="201">返回新创建的项目</response>
/// <response code="400">如果item是null</response>
[HttpPost]
[ProducesResponseType(typeof(dotNetCore_Test1.Models.User), )]
[ProducesResponseType(typeof(dotNetCore_Test1.Models.User), )]
[HttpPost]
public IActionResult Post([FromBody]dotNetCore_Test1.Models.User item)
{
if (item == null)
{
return BadRequest();
}
return Ok(item);
} /// <summary>
/// 删除一个对象
/// </summary>
/// <remarks>
/// 这里可以写详细的备注
/// </remarks>
/// <param name="id">主键id标识</param>
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}

13、通过访问 http://localhost:<random_port>/swagger/ui 查看Swagger 自动生成文档 (<random_port> 表示IIS Express随机分配的端口号,我测试的demo分配的端口号是:51109,所以我这里查看Swagger生成的文档地址是http://localhost:51109/swagger/ui/index.html#/Values)生成的文档如下图:

13.1、

13.2

13.3

13.4

配置 Swagger 使用生成的 XML 文件

使用 Swagger 自动生成 ASP.NET Core Web API 的文档、在线帮助测试文档(ASP.NET Core Web API 自动生成文档)的更多相关文章

  1. xcode 自动添加注释,生成文档

    一.自动生成注释代码        添加一个快捷键,生成 注释代码        ThisService 下载连接:http://wafflesoftware.net/thisservice/     ...

  2. 使用Sphinx为你的python模块自动生成文档

    Sphinx是一个可以用于Python的自动文档生成工具,可以自动的把docstring转换为文档,并支持多种输出格式包括html,latex,pdf等. 安装 创建一个sphinx项目 下面的命令会 ...

  3. ASP.NET Core 1.0 中使用 Swagger 生成文档

    github:https://github.com/domaindrivendev/Ahoy 之前文章有介绍在ASP.NET WebAPI 中使用Swagger生成文档,ASP.NET Core 1. ...

  4. 使用swagger在netcorewebapi项目中自动生成文档

    一.背景 随着前后端分离模式大行其道,我们需要将后端接口撰写成文档提供给前端,前端可以查看我们的接口,并测试,提高我们的开发效率,减少无效的沟通.在此情况下,通过代码自动生成文档,这种需求应运而生,s ...

  5. MVC WEB api 自动生成文档

    最近在一直在用webapi做接口给移动端用.但是让我纠结的时候每次新加接口或者改动接口的时候,就需要重新修改文档这让我很是苦恼.无意中发现.webapi居然有自动生成文档的功能....真是看见了救星啊 ...

  6. swagger生成文档初步使用

    在大部分情况下,公司都会要求提供详细的接口文档,对于开发来说,文档有时候在赶进度的情况下,也是一件头疼的事.而swagger的自动生成文档功能,就可以帮助我们减少工作量,对于文档的修改也可以在代码中随 ...

  7. SpringBoot 集成Swagger2自动生成文档和导出成静态文件

    目录 1. 简介 2. 集成Swagger2 2.1 导入Swagger库 2.2 配置Swagger基本信息 2.3 使用Swagger注解 2.4 文档效果图 3. 常用注解介绍 4. Swagg ...

  8. eoLinker 新功能发布,增加了识别代码注释自动生成文档功能

    产品地址:https://www.eolinker.com开源代码:https://www.eolinker.com/#/os/download在线生成代码注释工具:http://tool.eolin ...

  9. 用doxygen自动生成文档

    1. 添加符合doxygen解析规则的注释 (比如函数说明,函数参数/返回值说明) 用qt-creator可以在函数上方一行键入“/**”,然后直接回车,就可以自动生成默认的格式. 2. 安装doxy ...

随机推荐

  1. IE10、IE11 User-Agent 导致的 ASP.Net 网站无法写入Cookie 问题

    你是否遇到过当使用一个涉及到Cookie操作的网站或者管理系统时,IE 6.7.8.9下都跑的好好的,唯独到了IE10.11这些高版本浏览器就不行了?好吧,这个问题码农连续2天内遇到了2次.那么,我们 ...

  2. Web APi之认证(Authentication)两种实现方式【二】(十三)

    前言 上一节我们详细讲解了认证及其基本信息,这一节我们通过两种不同方式来实现认证,并且分析如何合理的利用这两种方式,文中涉及到的基础知识,请参看上一篇文中,就不再叙述废话. 序言 对于所谓的认证说到底 ...

  3. C#如何在PDF文件添加图片印章

    文档中添加印章可以起一定的作用,比如,防止文件随意被使用,或者确保文档内容的安全性和权威性.C#添加图片印章其实也有很多实现方法,这里我使用的是免费的第三方软件Free Spire.PDF,向大家阐述 ...

  4. java单向加密算法小结(1)--Base64算法

    从这一篇起整理一下常见的加密算法以及在java中使用的demo,首先从最简单的开始. 简单了解 Base64严格来说并不是一种加密算法,而是一种编码/解码的实现方式. 我们都知道,数据在计算机网络之间 ...

  5. JavaScript 常量定义

    相信同学们在看见这个标题的时候就一脸懵逼了,什么?JS能常量定义?别逗我好吗?确切的说,JS当中确实没有常量(ES6中好像有了常量定义的关键字),但是深入一下我们可以发现JS很多不为人知的性质,好好利 ...

  6. 代码的坏味道(16)——纯稚的数据类(Data Class)

    坏味道--纯稚的数据类(Data Class) 特征 纯稚的数据类(Data Class) 指的是只包含字段和访问它们的getter和setter函数的类.这些仅仅是供其他类使用的数据容器.这些类不包 ...

  7. 根据ip判断返回城市名称查询当地天气

    <?phpheader("content-type:text/html;charset=utf-8");date_default_timezone_set("Asi ...

  8. JDBC Tutorials: Commit or Rollback transaction in finally block

    http://skeletoncoder.blogspot.com/2006/10/jdbc-tutorials-commit-or-rollback.html JDBC Tutorials: Com ...

  9. BZOJ 1391: [Ceoi2008]order [最小割]

    1391: [Ceoi2008]order Time Limit: 10 Sec  Memory Limit: 64 MBSubmit: 1509  Solved: 460[Submit][Statu ...

  10. [每日Linux]Linux下xsell和xftp的使用

    实验缘由: 1.xsell在Linux下的作用就是远程登录的一个界面,也就是实现访问在Windows下访问Linux服务器的功能.之前在数据挖掘实验中因为自己电脑的内存不够,曾经使用过实验室的服务器跑 ...