ASP.NET CORE 1.0 MVC API 文档用 SWASHBUCKLE SWAGGER实现

本文涉及的产品
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
简介:

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.

SwaggerProjectConfig

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

aspnet5Mvc6Swagger_02

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();
}
}
复制代码

}




本文转自94cool博客园博客,原文链接:http://www.cnblogs.com/94cool/p/5694881.html,如需转载请自行联系原作者

相关实践学习
使用阿里云Elasticsearch体验信息检索加速
通过创建登录阿里云Elasticsearch集群,使用DataWorks将MySQL数据同步至Elasticsearch,体验多条件检索效果,简单展示数据同步和信息检索加速的过程和操作。
ElasticSearch 入门精讲
ElasticSearch是一个开源的、基于Lucene的、分布式、高扩展、高实时的搜索与数据分析引擎。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr(也是基于Lucene)。 ElasticSearch的实现原理主要分为以下几个步骤: 用户将数据提交到Elastic Search 数据库中 通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据 当用户搜索数据时候,再根据权重将结果排名、打分 将返回结果呈现给用户 Elasticsearch可以用于搜索各种文档。它提供可扩展的搜索,具有接近实时的搜索,并支持多租户。
相关文章
|
29天前
|
敏捷开发 测试技术 API
云效产品使用常见问题之代码仓库不支持API文档如何解决
云效作为一款全面覆盖研发全生命周期管理的云端效能平台,致力于帮助企业实现高效协同、敏捷研发和持续交付。本合集收集整理了用户在使用云效过程中遇到的常见问题,问题涉及项目创建与管理、需求规划与迭代、代码托管与版本控制、自动化测试、持续集成与发布等方面。
|
29天前
|
数据可视化 Linux API
如何在Linux使用docker部署Swagger Editor并实现无公网IP远程协同编辑API文档
如何在Linux使用docker部署Swagger Editor并实现无公网IP远程协同编辑API文档
|
18小时前
|
数据可视化 Java API
【JAVA】javadoc,如何生成标准的JAVA API文档
【JAVA】javadoc,如何生成标准的JAVA API文档
6 0
|
6天前
|
XML 前端开发 Java
Spring3 MVC中使用Swagger生成API文档
Spring3 MVC中使用Swagger生成API文档
10 0
|
6天前
|
JSON 前端开发 API
Apache HttpClient调用Spring3 MVC Restful Web API演示
Apache HttpClient调用Spring3 MVC Restful Web API演示
11 1
|
7天前
|
Linux C# C++
【.NET Developer】创建ASP.NET Core Blazor项目并打包为Linux镜像发布到Azure应用服务
本文介绍了如何使用VS2019和.NET框架创建一个Blazor应用,并将其部署到Azure应用服务。首先,Blazor是一个使用C#而非JavaScript构建交互式Web UI的框架,支持共享服务器和客户端应用逻辑,以及与Docker和Azure集成。任务包括创建Blazor项目,配置Dockerfile为Linux容器,本地测试,发布到Azure Container Registry (ACR),然后在Azure App Service for Container上部署。在部署过程中,需确保Docker设置正确,开启ACR的Admin访问权限,并监控镜像拉取和容器启动日志。
|
8天前
|
开发框架 .NET API
ASP.NET Core Web中使用AutoMapper进行对象映射
ASP.NET Core Web中使用AutoMapper进行对象映射
|
20天前
|
前端开发 JavaScript 中间件
基于最新koa的Node.js后端API架构与MVC模式
基于最新koa的Node.js后端API架构与MVC模式
30 1
|
20天前
|
API
1天搞定SpringBoot+Vue全栈开发 (2)RESTful API与Swagger
1天搞定SpringBoot+Vue全栈开发 (2)RESTful API与Swagger
|
29天前
|
测试技术 API 开发工具
📑教你如何编写一份 API 文档
API 文档是开发者理解和使用API的关键,它提供详细的说明、代码示例和调用过程,帮助创建无缝集成。好的API文档能提升开发人员体验,减少上手时间和维护成本,同时促进产品迭代。API有面向团队、合作伙伴和最终用户三种类型。编写文档时要考虑受众,提供清晰的概述、教程、认证信息、端点定义、状态码和错误码示例。维护更新与API同步的文档至关重要,遵循通俗语言、参考文档、示例和专人负责等最佳实践,确保全面性。GitHub、Twilio和Dropbox的API文档是良好示例。