Ocelot网关配置后访问微服务路由返回404问题咨询
问题根因排查
1. 核心问题:中间件注册顺序错误
ASP.NET Core 中间件按注册顺序依次执行,你当前代码将app.UseOcelot()放在了app.UseEndpoints()之后,请求进入后会先匹配本地控制器路由,找不到对应路由就直接返回404,完全不会进入Ocelot的处理逻辑。
2. 其他可能的衍生问题
- Ocelot配置文件未设置重载和可选参数,修改配置或环境切换时可能出现加载失败
- 认证、授权中间件若仅为本地接口服务,放在Ocelot之前会导致网关转发的请求被提前校验拦截
- 下游服务使用自签名HTTPS证书时,网关默认会校验证书有效性,校验失败也会返回异常
解决方法
- 调整中间件注册顺序,将
app.UseOcelot()移到app.UseEndpoints()之前,调整后的Configure方法参考如下:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseSerilogRequestLogging(); app.UseCors(_AllowSpecificOrigin); app.UseSwagger(options => { options.SerializeAsV2 = true; }); app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "ShoppingCart API"); options.RoutePrefix = string.Empty; }); // Ocelot注册移到Endpoints之前,老版本Ocelot需要加Wait()处理异步逻辑 app.UseOcelot().Wait(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapControllerRoute( "default", "{controller=Products}/{action=GetAll}/{id?}"); }); }
- 优化Ocelot配置加载逻辑,避免配置加载异常:
webBuilder.ConfigureAppConfiguration(config => { config .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true) .AddJsonFile($"ocelot.{environment}.json", optional: true, reloadOnChange: true); });
- 本地开发场景如果下游服务使用自签名证书,可在路由配置中临时关闭证书校验:
{ "Routes": [ { "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 7001 } ], "DownstreamPathTemplate": "/order", "DownstreamScheme": "https", "UpstreamPathTemplate": "/order", "UpstreamHttpMethod": [ "GET" ], "DangerousAcceptAnyServerCertificateValidator": true } ] }
内容的提问来源于stack exchange,提问作者dotnetlooper
相关产品推荐
相关产品推荐

