ASP.NET CORE 1.0 MVC API 文档用 SWASHBUCKLE SWAGGER实现
from:https://damienbod.com/2015/12/13/asp-net-5-mvc-6-api-documentation-using-swagger/
代码生成工具: https://github.com/NSwag/NSwag
This article shows how to document your ASP.NET Core 1.0 MVC API using Swagger with Swashbuckle. Per default, it does not use your xml comments in the code and this needs to be configured if required.
Code: https://github.com/damienbod/AspNet5GeoElasticsearch
2016.07.03 Updated to ASP.NET Core RTM
2016.06.04 Updated to ASP.NET Core RC2 dotnet
Step 1: Add the required NuGet packages to the dependencies in the project.json file.
|
1
2
3
4
5
6
|
"dependencies": { "Swashbuckle.SwaggerGen": "6.0.0-beta901", "Swashbuckle.SwaggerUi": "6.0.0-beta901"}, |
Step 2: Produce the .xml file which contains the xml comments when building. Click the produce outputs on build checkbox in your project file.

Or set the ProduceOutputsOnBuild property in the project xproj file.
|
1
|
<ProduceOutputsOnBuild>True</ProduceOutputsOnBuild> |
Step 3: Configure Swashbuckle.SwaggerGen in the Startup class ConfigureServices method.
You need to define your path to the comments xml file, which can be found in the artifacts folder. This should be saved in a config file.
The ConfigureSwaggerDocument with OperationFilter method is required so that the xml comments are added to the documentation, and also ConfigureSwaggerSchema with ModelFilter
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public void ConfigureServices(IServiceCollection services){ var pathToDoc = Configuration["Swagger:Path"]; services.AddMvc(); services.AddSwaggerGen(); services.ConfigureSwaggerGen(options => { options.SingleApiVersion(new Info { Version = "v1", Title = "Geo Search API", Description = "A simple api to search using geo location in Elasticsearch", TermsOfService = "None" }); options.IncludeXmlComments(pathToDoc); options.DescribeAllEnumsAsStrings(); }); services.AddScoped<ISearchProvider, SearchProvider>();} |
Step 4: Use swagger in the Startup class Configure method.
UseSwaggerGen and UseSwaggerUi
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){ loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.UseSwagger(); app.UseSwaggerUi();} |
Step 5: Create a Controller API with your documentation:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
using Microsoft.AspNet.Mvc;using AspNet5GeoElasticsearch.ElasticsearchApi;using AspNet5GeoElasticsearch.Models;using Newtonsoft.Json;using Swashbuckle.SwaggerGen.Annotations;namespace AspNet5GeoElasticsearch.Controllers{ /// <summary> /// This class is used as an api for the search requests. /// </summary> [Route("api/[controller]")] [Produces("application/json")] public class SearchController : Controller { private readonly ISearchProvider _searchProvider; public SearchController(ISearchProvider searchProvider) { _searchProvider = searchProvider; } /// <summary> /// This method returns the found documents from Elasticsearch /// </summary> /// <param name="maxDistanceInMeter">Distance in meters from your location</param> /// <param name="centerLongitude">center Longitude </param> /// <param name="centerLatitude">center Latitude </param> /// <returns>All the documents which were found</returns> [HttpGet] [Produces(typeof(MapModel))] [SwaggerResponse(System.Net.HttpStatusCode.OK, Type = typeof(MapModel))] [Route("GeoSearch")] public ActionResult Search(uint maxDistanceInMeter, double centerLongitude, double centerLatitude) { var searchResult = _searchProvider.SearchForClosest(maxDistanceInMeter, centerLongitude, centerLatitude); var mapModel = new MapModel { MapData = JsonConvert.SerializeObject(searchResult), CenterLongitude = centerLongitude, CenterLatitude = centerLatitude, MaxDistanceInMeter = maxDistanceInMeter }; return Ok(mapModel); } /// <summary> /// Inits the Elasticsearch documents /// </summary> [HttpPost] [Route("InitData")] public ActionResult InitData() { initSearchEngine(); return Ok(); } private void initSearchEngine() { if (!_searchProvider.MapDetailsIndexExists()) { _searchProvider.InitMapDetailMapping(); _searchProvider.AddMapDetailData(); } } }} |
This can then be viewed using ./swagger/ui
http://localhost:21453/swagger/ui/index.html

Links:
https://github.com/domaindrivendev/Swashbuckle
https://github.com/domaindrivendev/Ahoy
http://blog.sluijsveld.com/28/01/2016/CustomSwaggerUIField/
修改文档名称及路径:
using System;
using System.Collections.Generic;
using System.IO;
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 Swashbuckle.Swagger.Model;
using Swashbuckle.SwaggerGen.Application; namespace CoreApi
{
/// <summary>
///
/// </summary>
public class Startup
{
/// <summary>
/// 必须,不允许为空字符串
/// </summary>
string version = "v1";
/// <summary>
/// API文档路径
/// </summary>
string pathToDoc = Path.Combine(AppContext.BaseDirectory, "CoreApi.xml");
/// <summary>
/// API项目名称
/// </summary>
string appName = "CoreApi";
/// <summary>
///
/// </summary>
/// <param name="env"></param>
public Startup(IHostingEnvironment env)
{
appName = env.ApplicationName;
pathToDoc = Path.Combine(AppContext.BaseDirectory, string.Format("{0}.xml", env.ApplicationName));
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables(); Configuration = builder.Build();
}
/// <summary>
///
/// </summary>
public IConfigurationRoot Configuration
{
get;
} // This method gets called by the runtime. Use this method to add services to the container.
/// <summary>
///
/// </summary>
/// <param name="services"></param>
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc(); services.AddSwaggerGen();
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = version,
Title = appName,
Description = appName,
TermsOfService = "None",
});
options.IncludeXmlComments(pathToDoc);
options.DescribeAllEnumsAsStrings();
});
//services.AddScoped<ISearchProvider, SearchProvider>();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// <summary>
///
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
/// <param name="loggerFactory"></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseSwagger("help/{apiVersion}/api.json");
app.UseSwaggerUi("help", string.Format("/help/{0}/api.json", version));
app.UseMvc();
}
}
}
搜索
复制
ASP.NET CORE 1.0 MVC API 文档用 SWASHBUCKLE SWAGGER实现的更多相关文章
- 用VSCode开发一个asp.net core2.0+angular5项目(5): Angular5+asp.net core 2.0 web api文件上传
第一部分: http://www.cnblogs.com/cgzl/p/8478993.html 第二部分: http://www.cnblogs.com/cgzl/p/8481825.html 第三 ...
- 从头编写 asp.net core 2.0 web api 基础框架 (1)
工具: 1.Visual Studio 2017 V15.3.5+ 2.Postman (Chrome的App) 3.Chrome (最好是) 关于.net core或者.net core 2.0的相 ...
- 【转载】从头编写 asp.net core 2.0 web api 基础框架 (1)
工具: 1.Visual Studio 2017 V15.3.5+ 2.Postman (Chrome的App) 3.Chrome (最好是) 关于.net core或者.net core 2.0的相 ...
- ASP.NET Core 2.0 MVC项目实战
一.前言 毕业后入职现在的公司快有一个月了,公司主要的产品用的是C/S架构,再加上自己现在还在学习维护很老的delphi项目,还是有很多不情愿的.之前实习时主要是做.NET的B/S架构的项目,主要还是 ...
- asp.net core 3.0 MVC JSON 全局配置
asp.net core 3.0 MVC JSON 全局配置 System.Text.Json(default) startup配置代码如下: using System.Text.Encodings. ...
- 从头编写 asp.net core 2.0 web api 基础框架 (3)
第一部分:http://www.cnblogs.com/cgzl/p/7637250.html 第二部分:http://www.cnblogs.com/cgzl/p/7640077.html 之前我介 ...
- 【转载】从头编写 asp.net core 2.0 web api 基础框架 (3)
Github源码地址:https://github.com/solenovex/Building-asp.net-core-2-web-api-starter-template-from-scratc ...
- 从头编写asp.net core 2.0 web api 基础框架 (5) + 使用Identity Server 4建立Authorization Server (7) 可运行前后台源码
前台使用angular 5, 后台是asp.net core 2.0 web api + identity server 4. 从头编写asp.net core 2.0 web api 基础框架: 第 ...
- asp.net core 2.0 web api + Identity Server 4 + angular 5 可运行前后台源码
前台使用angular 5, 后台是asp.net core 2.0 web api + identity server 4. 从头编写asp.net core 2.0 web api 基础框架: 第 ...
随机推荐
- Android中的Interpolator
Android中的Interpolator Interpolator用于动画中的时间插值,其作用就是把0到1的浮点值变化映射到另一个浮点值变化. 本文列出Android API提供的Interpola ...
- dispatch
GCD提供了并管理着若干FIFO队列(queues),可以通过block的形式向这些FIFO序列提交任务.GCD同时维护着一个线程池,所有的任务在线程池的线程运行. 系统提供的队列 main queu ...
- 操作系统开发系列—12.d.扩充内核 ●
现在把esp.GDT等内容放进内核中,我们现在可以用C语言了,只要能用C,我们就避免用汇编. 下面看切换堆栈和GDT的关键代码: ; 导入函数 extern cstart ; 导入全局变量 exter ...
- 操作系统开发系列—11.ELF格式 ●
ELF文件的结构如下图所示: ELF文件由4部分组成,分别是ELF头(ELF header).程序头表(Program header table).节(Sections)和节头表(Section he ...
- eclipse怎样在线安装hibernate tools插件并使用
不知不觉,小Alan已经将近3个月没有上班了,最近在复习一些知识,随时准备回到代码世界的战场,今天复习到了Hibernate,记录一下一点点小知识,那就是eclipse下hibernate Tools ...
- 软工_Alpha阶段事后分析总计
1.设想和目标 1.1 我们的软件要解决什么问题?是否定义得很清楚?是否对典型用户和典型场景有清晰的描述? 我们的软件主要解决狼人杀玩家在游戏时的一些痛点.因为之前自己对于游戏中那些不方便的地方有过体 ...
- 《Google想出了一个决定人员晋升的算法,然后就没有然后了......》有感
Prasad Setty 是 Google People Analytics 团队的副总裁.7 年前 Google 成立的这支团队的职责是收集和利用数据来支撑公司的管理实践.其使命很简单,即基于数据和 ...
- ORACLE SQL调优案例一则
收到监控告警日志文件(Alert)的作业发出的告警邮件,表空间TEMPSCM2不能扩展临时段,说明临时表空间已经被用完了,TEMPSCM2表空间不够用了 Dear All: The Instanc ...
- 海量IT资料 + 各种平台下的Oracle安装文件 + 公开课录像 + 各种视频教程资料
觉得老师的公开课讲的都挺好的,这里把我录的一些公开课视频分享给大家,都用的是<屏幕录像专家>来录制的,是lxe格式的,大家用这个软件来播放就可以了,后边的公开课录像文件也会慢慢添加进去的, ...
- iOS tabbar 自定义小红点 消息显示,定制边框、颜色、高宽
一般我们需要显示消息数,会利用到系统提供的api UIApplication.sharedApplication().applicationIconBadgeNumber = 10 但如果我们不想显示 ...