引言
Swagger就是最受欢迎的REST APIs文档生成工具
asp.net core中如何使用Swagger生成api说明文档呢
- Swashbuckle.AspNetCore 是一个开源项目,用于生成 ASP.NET Core Web API 的 Swagger 文档。
- NSwag 是另一个用于将 Swagger UI 或 ReDoc 集成到 ASP.NET Core Web API 中的开源项目。 它提供了为 API 生成 C# 和 TypeScript 客户端代码的方法。
以Swashbuckle.AspNetCore为例生产api说明文档
Swashbuckle组成部分
- Swashbuckle.AspNetCore.Swagger:将 SwaggerDocument 对象公开为 JSON 终结点的 Swagger 对象模型和中间件。
- Swashbuckle.AspNetCore.SwaggerGen:从路由、控制器和模型直接生成 SwaggerDocument 对象的 Swagger 生成器。 它通常与 Swagger 终结点中间件结合,以自动公开 Swagger JSON。
- Swashbuckle.AspNetCore.SwaggerUI:Swagger UI 工具的嵌入式版本。 它解释 Swagger JSON 以构建描述 Web API 功能的可自定义的丰富体验。 它包括针对公共方法的内置测试工具。
步骤
- 使用nuget下载Swashbuckle.AspNetCore
- 打开项目Startup.cs文件,将 Swagger 生成器添加到 ConfigureServices 方法中的服务集合中
//注册Swagger生成器,定义一个和多个Swagger 文档
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
- Configure方法中,启用中间件为生成的 JSON 文档和 Swagger UI 提供服务:
//启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();
//启用中间件服务对swagger-ui,指定Swagger JSON终结点
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
- 启动应用,并导航到 http://localhost:<port>/swagger/v1/swagger.json。 生成的描述终结点的文档显示如下json格式。
- 可在 http://localhost:<port>/swagger 找到 Swagger UI。 通过 Swagger UI 浏览 API文档,如下所示。
- 要在应用的根 (http://localhost:<port>/) 处提供 Swagger UI,请将 RoutePrefix 属性设置为空字符串:
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty;
});
Swagger的高级用法 为文档添加注释
7.1. 在接口上添加文档注释/// 7.2. 运行项目,发现swaggerUI并没有出现注释 (别急,往下看) 7.3. 启用XML 注释
右键单击“解决方案资源管理器”中的项目,然后选择“属性”
查看“生成”选项卡的“输出”部分下的“XML 文档文件”框
注意上面生成的xml文档文件的路径
7.4. 再次修改Startup.cs文件的ConfigureServices 方法,AddSwaggerGen()方法中读取xml文件路径并启用
//注册Swagger生成器,定义一个和多个Swagger 文档
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
// 为 Swagger JSON and UI设置xml文档注释路径
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
var xmlPath = Path.Combine(basePath, "TestCoreSwagger.xml");
c.IncludeXmlComments(xmlPath);
});
7.5. 新生成并运行项目 注释就出来了
配置Swagger
打开launchSettings.json文件,修改如下
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false, //启用Windows身份验证
"anonymousAuthentication": true, //启用匿名身份验证
"iisExpress": {
"applicationUrl": "http://localhost:62671", //应用启动的Url路径。
"sslPort": 44359 //启用SSL的端口
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true, //是否在浏览器中启动
"launchUrl": "swagger/index.html", //在浏览器中启动的相对URL
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" //将环境变量设置为键/值对
}
},
"TestCoreApi": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger/index.html",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
意思是这样的,看下图
在如下位置添加swagger_lang.js
'use strict';
/**
* Translator for documentation pages.
*
* To enable translation you should include one of language-files in your index.html
* after <script src='lang/translator.js' type='text/javascript'></script>.
* For example - <script src='lang/ru.js' type='text/javascript'></script>
*
* If you wish to translate some new texsts you should do two things:
* 1. Add a new phrase pair ("New Phrase": "New Translation") into your language file (for example lang/ru.js). It will be great if you add it in other language files too.
* 2. Mark that text it templates this way <anyHtmlTag data-sw-translate>New Phrase</anyHtmlTag> or <anyHtmlTag data-sw-translate value='New Phrase'/>.
* The main thing here is attribute data-sw-translate. Only inner html, title-attribute and value-attribute are going to translate.
*
*/
window.SwaggerTranslator = {
_words: [],
translate: function () {
var $this = this;
$('[data-sw-translate]').each(function () {
$(this).html($this._tryTranslate($(this).html()));
$(this).val($this._tryTranslate($(this).val()));
$(this).attr('title', $this._tryTranslate($(this).attr('title')));
});
},
_tryTranslate: function (word) {
return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word;
},
learn: function (wordsMap) {
this._words = wordsMap;
}
};
/* jshint quotmark: double */
window.SwaggerTranslator.learn({
"Warning: Deprecated": "警告:已过时",
"Implementation Notes": "实现备注",
"Response Class": "响应类",
"Status": "状态",
"Parameters": "参数",
"Parameter": "参数",
"Value": "值",
"Description": "描述",
"Parameter Type": "参数类型",
"Data Type": "数据类型",
"Response Messages": "响应消息",
"HTTP Status Code": "HTTP状态码",
"Reason": "原因",
"Response Model": "响应模型",
"Request URL": "请求URL",
"Response Body": "响应体",
"Response Code": "响应码",
"Response Headers": "响应头",
"Hide Response": "隐藏响应",
"Headers": "头",
"Try it out!": "试一下!",
"Show/Hide": "显示/隐藏",
"List Operations": "显示操作",
"Expand Operations": "展开操作",
"Raw": "原始",
"can't parse JSON. Raw result": "无法解析JSON. 原始结果",
"Model Schema": "模型架构",
"Model": "模型",
"apply": "应用",
"Username": "用户名",
"Password": "密码",
"Terms of service": "服务条款",
"Created by": "创建者",
"See more at": "查看更多:",
"Contact the developer": "联系开发者",
"api version": "api版本",
"Response Content Type": "响应Content Type",
"fetching resource": "正在获取资源",
"fetching resource list": "正在获取资源列表",
"Explore": "浏览",
"Show Swagger Petstore Example Apis": "显示 Swagger Petstore 示例 Apis",
"Can't read from server. It may not have the appropriate access-control-origin settings.": "无法从服务器读取。可能没有正确设置access-control-origin。",
"Please specify the protocol for": "请指定协议:",
"Can't read swagger JSON from": "无法读取swagger JSON于",
"Finished Loading Resource Information. Rendering Swagger UI": "已加载资源信息。正在渲染Swagger UI",
"Unable to read api": "无法读取api",
"from path": "从路径",
"server returned": "服务器返回"
});
$(function () {
window.SwaggerTranslator.translate();
});
修改startup.cs,完整文件代码如下:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//注册Swagger生成器,定义一个和多个Swagger 文档
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
// 为 Swagger JSON and UI设置xml文档注释路径
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
var xmlPath = Path.Combine(basePath, "TestCoreSwagger.xml");
c.IncludeXmlComments(xmlPath);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
//启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();
//启用中间件服务对swagger-ui,指定Swagger JSON终结点
app.UseSwaggerUI(c =>
{
c.DocExpansion(DocExpansion.None); //设置swagger 默认折叠
c.DefaultModelsExpandDepth(-1);//设置不显示models
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.InjectJavascript( "/content/swaggerui/swagger_lang.js");
});
app.UseHttpsRedirection();
//app.UseMvc();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Values}/{action=Get}/{id?}");
}); //将MVC添加到管道并允许配置路
}
}
版权属于:dingzhenhua
本文链接:https://www.dcmickey.cn/skill/17.html
转载时须注明出处及本声明
最后一次更新于2020-03-17
0 条评论