一日一技:在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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 宠粉老鱼皮带你 “入坑” GitHub!
- 下一篇: 使用GZipStream实现压缩和解压缩