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实现相关推荐

  1. ASP.NET Core 5.0 Web API 自动集成Swashbuckle

    ASP.NET Core 5.0 Web API与开放源代码项目 Swashbuckle.AspNetCore 的维护人员合作,ASP.NET Core API 模板包含对 Swashbuckle 的 ...

  2. ASP.NET Core 2.0 MVC项目实战

     一.前言 毕业后入职现在的公司快有一个月了,公司主要的产品用的是C/S架构,再加上自己现在还在学习维护很老的delphi项目,还是有很多不情愿的.之前实习时主要是做.NET的B/S架构的项目,主要还 ...

  3. 从头编写 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的相 ...

  4. 用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 第三 ...

  5. 【转载】从头编写 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的相 ...

  6. 从头编写 asp.net core 2.0 web api 基础框架 (2)

    上一篇是: 从头编写 asp.net core 2.0 web api 基础框架 (1) Github源码地址是: https://github.com/solenovex/Building-asp. ...

  7. 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 基础框架: 第 ...

  8. Asp.Net Core 6.0 Mvc入门 图书查询系统 附带源码下载

    Asp.Net Core 6.0 MVC 入门 简介 目标 第一章 创建Asp.Net Core Web应用 第二章 从Model开始 第三章 Model之后皆基架 第四章 运行应用 第五章 数据搜索 ...

  9. 在ASP.NET Core中如何将各种文档合并为PDF?Aspose快速搞定!

    在各种业务环境中,将各种文档合并为一个PDF是客户最常问的问题之一.例如,假设您的组织有多个应用程序以XPS和PDF生成特定的文档,使用扫描的图像,并且您的用户希望将其中一些文档合并为一个PDF. 本 ...

最新文章

  1. 考研常识:研究生单独考试是什么意思?
  2. 第七讲 一阶常系数线性ODE
  3. Windows 10——连接鼠标时触摸板失效解决方案
  4. Python多任务(1.多任务的介绍、并发和并行概念及小例子)
  5. DCMTK:dcmseg模块的辅助功能
  6. fork 与 branch、clone 的区别
  7. JM与h264标准中的关键字说明
  8. 漫步线性代数三——高斯消元法
  9. MySQL访问行更新慢、用户线程大量堆积竟是因为它
  10. 异构计算 软硬协同设计_优雅的设计CNN并行架构-软硬协同之位宽设置(2)
  11. ggthemes包:丰富ggplot2的表现力
  12. Linux如何关闭自动锁屏
  13. 产品经理素质能力模型
  14. TCP序列号(Sequence Number)和确认号(Acknowledgment Number)
  15. 修改IDEA默认运行内存
  16. SAE使用以及GPS 的经纬度换算成距离的代码(转载)
  17. mac book pro高清录屏教程(obs录屏+麦克风录制+soundflower电脑声录制)三合一
  18. Flutter 使用自定义 fluro 路由转场动画实现个性化页面切换
  19. 世界人工智能大会即将举办 AI机器人帮你分类垃圾
  20. vue h5分享微信节日头像合成”

热门文章

  1. 3.4 usermod命令 3.5 用户密码管理 3.6 mkpasswd命令
  2. 使用vim保存权限不够的文件
  3. 怎么解决tomcat占用8080端口问题图文教程
  4. linux笔记第一章--基本命令记载
  5. 内容激活码jsp发送email
  6. 伪静态技术(SEO) 摘自:http://bbs.admin5.com/thread-8522290-1-1.html
  7. 开源游戏地图编辑器 Mepper
  8. PowerPoint发布及链接图片的处理
  9. 互联网协议 — HTTPS 安全的超文本传输协议
  10. 我非要捅穿这 Neutron(二)上层资源模型篇