You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6 Ocelot网关404 NotFound问题排查求助

Ocelot网关404 NotFound问题排查求助

我已部署Ocelot API网关,同时拥有多个独立API,这些API通过自身URL在Postman中均可正常调用。但使用Ocelot配置的BaseUrl访问时,出现404 NotFound错误,请求协助排查问题。这是我第一次在此提问,若代码展示有误,敬请谅解。

网关项目代码(Program.cs)

var builder = WebApplication.CreateBuilder(args);

builder.Configuration
    .SetBasePath(builder.Environment.ContentRootPath)
    .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables();

builder.Services.AddOcelot(builder.Configuration);

// JWT 身份验证设置
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["AppSettings:ValidIssuer"],
            ValidAudience = builder.Configuration["AppSettings:ValidAudience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(builder.Configuration["AppSettings:Secret"]))
        };
    });

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthentication(); // JWT 身份验证
app.UseAuthorization();
await app.UseOcelot();
app.MapControllers();
app.Run();

Ocelot配置文件(ocelot.json)

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/Setting/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5004
        }
      ],
      "UpstreamPathTemplate": "/Setting/{everything}",
      "UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE" ],
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "Bearer",
        "AllowedScopes": []
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:5101"
  }
}

排查建议

  • 路由匹配检查:确认请求URL严格匹配UpstreamPathTemplate。比如下游API路径是http://localhost:5004/api/Setting/GetAll,则网关请求URL应为http://localhost:5101/Setting/GetAll,避免多写/漏写路径段。
  • 配置加载验证:检查ocelot.json的文件属性是否设置为「如果较新则复制」,确保程序运行时能读取到正确配置。可在启动时打印配置内容,验证Routes是否正确加载。
  • 中间件顺序确认:当前代码中await app.UseOcelot()的位置(UseAuthorization()之后、MapControllers()之前)是正确的,但需确保Ocelot中间件优先处理请求,避免被其他路由中间件拦截。
  • 排除认证干扰:暂时注释路由配置中的AuthenticationOptions,测试无认证情况下是否能正常转发,排除JWT认证导致的请求拦截(注:认证失败通常返回401,而非404,但仍可排查)。
  • 端口与协议一致性:确认下游API确实运行在http://localhost:5004,未启用HTTPS,与DownstreamScheme配置一致;同时确保网关访问地址为http://localhost:5101,而非HTTPS端口。
  • 启用Ocelot日志:在appsettings.json中添加日志配置,查看请求转发细节:
"Logging": {
  "LogLevel": {
    "Ocelot": "Debug",
    "Ocelot.Responder": "Debug",
    "Ocelot.DownstreamRouteFinder": "Debug"
  }
}

通过日志可确认请求是否匹配到路由,以及转发过程中的异常信息。

内容的提问来源于stack exchange,提问作者Betül

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 09:57:43