一日一技:在Ocelot网关中统一配置Swagger
共 5941字,需浏览 12分钟
·
2021-03-20 15:34
概述
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。在Ocelot网关中,我们提供给前端的直接是Swagger,如果Swagger分布在各个API中,前端查看Swagger的时候非常不便,Ocelot与Swagger的集成,方便在网关项目中统一查看各个服务的api文档。所以下面我们尝试把各个项目集合起来。
主要代码实现
1、客户端项目安装Swashbuckle.AspNetCore
2、ConfigureServices配置
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "客户端1 API", Version = "v1", Description = "# 客户端1 service api..." });
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
3、Configure配置
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "客户端1 API V1");
});
4、项目运行起来,http://localhost:5000/swagger/index.html
5、接下去是网关项目,安装如下
6、ConfigureServices配置
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new OpenApiInfo { Title = "网关test API", Version = "v1", Description = "# 网关test api..." });
});
services.AddOcelot(Configuration).AddConsul();
7、Configure配置
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "客户端1 API V1");
// c.SwaggerEndpoint("/product/swagger/v1/swagger.json", "Product API V1");
});
8、ocelot.json添加路由
{
"DownstreamPathTemplate": "/swagger/v1/swagger.json",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/swagger/v1/swagger.json",
"UpstreamHttpMethod": [ "Get" ],
"ServiceName": "ProductService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
},
9、最后,项目运行起来 http://localhost:5003/swagger/index.html
总结
1、在运行过程的时候会报错,如下
内部异常 1:
Exception: Unable to start Ocelot, errors are: Unable to start Ocelot, errors are: Unable to start Ocelot because either a ReRoute or GlobalConfiguration are using ServiceDiscoveryOptions but no ServiceDiscoveryFinderDelegate has been registered in dependency injection container. Are you missing a package like Ocelot.Provider.Consul and services.AddConsul() or Ocelot.Provider.Eureka and services.AddEureka()?,Unable to start Ocelot, errors are: Unable to start Ocelot because either a ReRoute or GlobalConfiguration are using ServiceDiscoveryOptions but no ServiceDiscoveryFinderDelegate has been registered in dependency injection container. Are you missing a package like Ocelot.Provider.Consul and services.AddConsul() or Ocelot.Provider.Eureka and services.AddEureka()?
问题原因: 容器中缺少相应的服务
解决办法:
install-package Ocelot.Provider.Consul
ConfigureServices服务注册中修改为 : services.AddOcelot(Configuration).AddConsul();
2、开源地址:https://gitee.com/conanOpenSource_admin/Example
.NET Core实战项目之CMS 第一章 入门篇-开篇及总体规划
【.NET Core微服务实战-统一身份认证】开篇及目录索引
Redis基本使用及百亿数据量中的使用技巧分享(附视频地址及观看指南)
.NET Core中的一个接口多种实现的依赖注入与动态选择看这篇就够了
用abp vNext快速开发Quartz.NET定时任务管理界面