欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

一日一技:在Ocelot网关中统一配置Swagger

发布时间:2023/12/4 46 豆豆
生活随笔 收集整理的这篇文章主要介绍了 一日一技:在Ocelot网关中统一配置Swagger 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

概述

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

总结

以上是生活随笔为你收集整理的一日一技:在Ocelot网关中统一配置Swagger的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。