1 swagger简介

Swagger是一个规范且完整的框架,提供描述、生产、消费和可视化RESTful Web Service。其核心是使用json来规范描述RESTful接口,另外有提供UI来查看接口说明,并有一套生成不同语言的客户端调用代码生成器。

1.1 对Api提供者

自顶向下

使用Swagger编辑器创建Swagger定义,然后使用Swagger代码生成工具生成服务器实现。

自底向上

为已有的REST API创建Swagger定义。一般的,Api提供者都会选择这种方式,比如在asp.net里集成swagger的支持,在写好接口代码之后,访问对应的swagger的访问Uri地址,就可以得到swagger.json。例如:http://petstore.swagger.io/v2/swagger.json

{
"swagger": "2.0",
"info": {
"tags": null,
"description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.",
"version": "1.0.0",
"title": "Swagger Petstore",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"email": "apiteam@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}
},
"host": "petstore.swagger.io",
"basePath": "/v2",
"tags": [
...

1.2 对Api使用者

使用swagger UI

一些提供者的站点会提供swagger ui来查看其swagger.json,例如:http://petstore.swagger.io/ 有了这些UI,自己手工编写客户端调用代码也非常简单了。

使用Swagger Codegen

可以Swagger Codegen的将swagger.json逆向生成你需要的客户端调用接口代码,本质上是使用了代码模板结合swagger.json描述来生成代码。在.net里,有一个Nswag项目,可以将swagger.json生成使用HttpClient来请求接口的c#代码。但是这些代码的质量也比较差,比如以下代码的HttpClient的生命周期也就无法很好的维护。

/// <summary>Add a new pet to the store</summary>
/// <param name="body">Pet object that needs to be added to the store</param>
/// <exception cref="SwaggerException">A server side error occurred.</exception>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
public async System.Threading.Tasks.Task AddPetAsync(Pet body, System.Threading.CancellationToken cancellationToken)
{
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/pet"); var client_ = new System.Net.Http.HttpClient();
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value));
content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
request_.Content = content_;
request_.Method = new System.Net.Http.HttpMethod("POST"); PrepareRequest(client_, request_, urlBuilder_);
var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
try
{
var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
if (response_.Content != null && response_.Content.Headers != null)
{
foreach (var item_ in response_.Content.Headers)
headers_[item_.Key] = item_.Value;
} ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString();
if (status_ == "405")
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new SwaggerException("Invalid input", (int)response_.StatusCode, responseData_, headers_, null);
}
else
if (status_ != "200" && status_ != "204")
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
}
}
finally
{
if (response_ != null)
response_.Dispose();
}
}
}
finally
{
if (client_ != null)
client_.Dispose();
}
}

2 WebApiClient.tools简介

WebApiClient是.net平台的一款RESTful声明式的面向切面客户端,其几乎100%实现了swagger定义的规范,WebApiClient.tools.swagger旨在将swagger.json逆向生成符合WebApiClient的声明式c#代码。

2.1 作用

使用原生HttpClient,你可能需要20行代码包装调用一个接口;使用WebApiClient,你可能只需要一行代码来定义接口方法;使用WebApiClient + WebApiClient.tools.swagger,你一行代码都不用写。

2.2 工作原理

  1. 使用NSwag解析json得到SwaggerDocument
  2. 使用RazorEngine将SwaggerDocument传入cshtml模板编译得到html
  3. 使用AngleSharp将html的文本代码提取,得到WebApiClient的声明式代码
  4. 代码美化,输出到本地文件

2.3 样例效果

接口代码

    /// <summary>
/// Everything about your Pets
/// </summary>
[TraceFilter]
[HttpHost("https://petstore.swagger.io/v2/")]
public interface IPetApi : IHttpApi
{
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name="body">Pet object that needs to be added to the store</param>
[HttpPost("pet")]
ITask<HttpResponseMessage> AddPetAsync( [Required] [JsonContent] Pet body ); /// <summary>
/// Update an existing pet
/// </summary>
/// <param name="body">Pet object that needs to be added to the store</param>
[HttpPut("pet")]
ITask<HttpResponseMessage> UpdatePetAsync( [Required] [JsonContent] Pet body ); ...

模型代码

    public class Pet
{
[AliasAs("id")]
public long? Id { get; set; } [AliasAs("category")]
public Category Category { get; set; } [AliasAs("name")]
[Required(AllowEmptyStrings = true)]
public string Name { get; set; } [AliasAs("photoUrls")]
[Required]
public List<string> PhotoUrls { get; set; } = new List<string>(); ...

3 相关资源

WebApiClient

github: https://github.com/dotnetcore/WebApiClient

WebApiClient.tools

github: https://github.com/xljiulang/WebApiClient.Tools

NSwag

github: https://github.com/RSuter/NSwag

RazorEngine

github: https://github.com/Antaris/RazorEngine

swagger文档转换为WebApiClient声明式代码的更多相关文章

  1. 使用 Swagger 文档化和定义 RESTful API

    大部分 Web 应用程序都支持 RESTful API,但不同于 SOAP API——REST API 依赖于 HTTP 方法,缺少与 Web 服务描述语言(Web Services Descript ...

  2. 懒得写文档,swagger文档导出来不香吗

    导航 前言 离线文档 1 保存为html 2 导出成pdf文档 3 导出成Word文档 参考 前言   早前笔者曾经写过一篇文章<研发团队,请管好你的API文档>.团队协作中,开发文档的重 ...

  3. 把office文档转换为html过程中的一些坑

    之前和我们项目的团队一起酝酿了一个项目,公司的业务文档技术文档比较多,但都比较分散,虽然通过FTP或其他方式聚合起来了,但感觉还是不够方便. 另外公司每次都来新员工,新员工都需要一些培训,比较耗时,比 ...

  4. revel + swagger 文档也能互动啦

    beego 从 1.3 后开始支持自动化API文档,不过,目测比较复杂,一直期望 revel 能有官方支持. revel 确实已经有了官方支持的计划,有可能将在 0.14 版本支持,现在才 0.11. ...

  5. Swagger文档转Word 文档

    GitHub 地址:https://github.com/JMCuixy/SwaggerToWord/tree/developer 原创作品,转载请注明出处:http://www.cnblogs.co ...

  6. 利用typescript生成Swagger文档

    项目地址:https://github.com/wz2cool/swagger-ts-doc demo代码地址:https://github.com/wz2cool/swagger-ts-doc-de ...

  7. 转:C#实现office文档转换为PDF或xps的一些方法

    代码支持任意office格式 需要安装office 2007 还有一个office2007的插件OfficeSaveAsPDFandXPS 下载地址 [url]http://www.microsoft ...

  8. PDF文档转换为图片、图片转成PDF 及PDF合并

    简介 功能:PDF文档按每页转换成一张图片,一张图片转换成一张PDF 并将多张PDF合成一个多页的PDF文档. 经历:在各个网站上搜索始终出现各种问题,尤其是遇到引用的版本问题尤其头疼,不是不能适用当 ...

  9. C#,VB.NET将PPT文档转换为HTML

    PPT文档主要用于展示,有时候我们需要将PPT文档转换为HTML格式方便查看.本文将介绍如何使用C#和VB.NET将PPT文档转换为HTML格式.该方案使用了.NET PowerPoint 组件Spi ...

随机推荐

  1. 数据保存策略(Retention Policies)

    数据保存策略(Retention Policies) InfluxDB没有提供直接删除Points的方法,但是它提供了Retention Policies.主要用于指定数据的保留时间:当数据超过了指定 ...

  2. hibernate MTM 联合主键

    //适用于表里没有其他列,只有主键 //Course.java实体类 package com.tao.pojo; import java.util.HashSet; import java.util. ...

  3. OKHttp源码学习--HttpURLConnection HttpClient OKHttp Get and post Demo用法对比

    1.HttpURLConnection public class HttpURLConnectionGetAndPost { private String urlAddress = "xxx ...

  4. Python:读取 .doc、.docx 两种 Word 文件简述及“Word 未能引发事件”错误

    概述 Python 中可以读取 word 文件的库有 python-docx 和 pywin32. 下表比较了各自的优缺点.   优点 缺点 python-docx 跨平台 只能处理 .docx 格式 ...

  5. Docker最全教程之Go实战,墙裂推荐(十八)

    前言 与其他语言相比,Go非常值得推荐和学习,真香!为什么?主要是可以直接编译成机器代码(性能优越,体积非常小,可达10来M,见实践教程图片)而且设计良好,上手门槛低.本篇主要侧重于讲解了Go语言的优 ...

  6. Spring Boot入门(一):使用IDEA创建Spring Boot项目并使用yaml配置文件

    由于公司最近在做技术转型(从.Net转Java),因此自己也开启了学习Java之路.学习Java怎么能不学习这几年这么火的Spring Boot框架,由于自己有总结的习惯,因此会把学习的过程以博客的形 ...

  7. Android 6.0 默认关闭定位和GPS,开启后默认选省电

    默认关闭定位和GPS 修改位置 frameworks/base/packages/SettingsProvider/res/values/defaults.xml <string name=&q ...

  8. Variable SQLLOGDIR not found

    昨天在一数据库(SQL Server 2008 R2 SP3)上部署了一个作业,今天早上收到告警邮件,作业执行报错"Unable to start execution of step 1 ( ...

  9. .Net Core 在Linux服务器下部署程序--(2). 部署前需要安装的软件及SDK

    安装通用软件 : ping , telnet , lrzsz , zip , wget 安装ping软件,用于测试当前服务器与其他服务器之间的网络通畅情况,和Windows的Ping类似 执行ping ...

  10. Storm入门(十)Twitter Storm: Transactional Topolgoy简介

    作者: xumingming | 可以转载, 但必须以超链接形式标明文章原始出处和作者信息及版权声明网址: http://xumingming.sinaapp.com/736/twitter-stor ...