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

Ocelot中间件触发404时刷新响应,StatusCodePages无法跳转自定义404页面

Ocelot 404自定义页面失效的解决办法

方案1:自定义错误响应处理器(推荐)

Ocelot允许通过实现IErrorsResponder接口替换默认的错误输出逻辑,直接在404触发时返回自定义重定向或页面内容,避免默认HTML页面生成。

实现自定义处理器:

public class CustomErrorResponder : IErrorsResponder
{
    public async Task Respond(HttpContext context, DownstreamResponse response)
    {
        if (response.StatusCode == HttpStatusCode.NotFound)
        {
            // 重定向到你的自定义404页面
            context.Response.Redirect("/error/404");
            return;
        }

        // 其他错误沿用Ocelot默认处理逻辑
        var defaultResponder = new ErrorsResponder();
        await defaultResponder.Respond(context, response);
    }
}

在服务注册时替换默认实现:

// Program.cs 或 Startup.cs
builder.Services.AddOcelot()
    .AddSingleton<IErrorsResponder, CustomErrorResponder>();

方案2:插入前置错误拦截中间件

通过在Ocelot中间件之前添加自定义中间件,在响应未被Ocelot修改前拦截404状态,提前执行重定向。注意要确保中间件顺序正确,放在UseOcelot()之前:

app.Use(async (context, next) =>
{
    await next();

    // 仅在响应未启动且状态码为404时处理
    if (context.Response.StatusCode == StatusCodes.Status404NotFound && !context.Response.HasStarted)
    {
        context.Response.Redirect("/error/404");
    }
});

// 注册Ocelot中间件
await app.UseOcelot();

方案3:通过Ocelot配置指定错误页

部分Ocelot版本支持在全局配置中指定错误重定向路径,直接在ocelot.json中添加配置:

{
  "GlobalConfiguration": {
    "BaseUrl": "https://your-gateway-domain",
    "ErrorHandler": {
      "RedirectTo": "/error/404",
      "StatusCode": 404
    }
  }
}

内容的提问来源于stack exchange,提问作者Milan Garg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:20:06