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

ASP.NET Core 8 Web API带参数路由经K8s Ingress访问报404

ASP.NET Core 8.0 Web API通过Kubernetes Ingress访问404问题解决

问题场景

本地调试时,http://localhost:8080/api/file/{appId}/{key}端点正常响应,但通过Kubernetes Ingress访问https://example.com/serviceapi/myservice/api/file/{appId}/{key}时返回404,其他API端点均正常。

核心原因分析

当前Ingress配置的路径重写规则与Ingress Controller类型不兼容,或重写逻辑有误,导致转发到后端的路径不符合ASP.NET Core的路由配置。

解决方案

方案1:调整Ingress重写规则(根据Ingress Controller类型选择)

情况A:使用Kubernetes官方NGINX Ingress Controller

官方控制器不支持nginx.org/rewrites注解,需替换为专属的重写注解并修改路径匹配规则:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: myservice.ingress
  namespace: myservice
  annotations:
    nginx.org/mergeable-ingress-type: "minion"
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  ingressClassName: nginx
  rules:
  - host: example.com
    http:
      paths:
      - path: /serviceapi/myservice/(.*)
        pathType: Prefix
        backend:
          service:
            name: myservice-webapi
            port:
              number: 80

此配置会将/serviceapi/myservice/之后的路径部分转发到后端根路径下,比如请求/serviceapi/myservice/api/file/1/2,后端实际收到/api/file/1/2,与本地调试的路由一致。

情况B:使用F5 NGINX Ingress Controller

若确认使用F5控制器,调整nginx.org/rewrites注解的重写规则,确保前缀正确替换:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: myservice.ingress
  namespace: myservice
  annotations:
    nginx.org/mergeable-ingress-type: "minion"
    nginx.org/rewrites: "serviceName=myservice-webapi rewrite=/serviceapi/myservice/(.*) /$1"
spec:
  ingressClassName: nginx
  rules:
  - host: example.com
    http:
      paths:
      - path: /serviceapi/myservice/
        pathType: Prefix
        backend:
          service:
            name: myservice-webapi
            port:
              number: 80

方案2:在ASP.NET Core中配置路径基础

无需修改Ingress,直接在Web API的Program.cs中添加路径基础配置,让应用识别/serviceapi/myservice作为前缀:

var builder = WebApplication.CreateBuilder(args);

// 其他服务配置...

var app = builder.Build();

// 添加路径基础配置
app.UsePathBase("/serviceapi/myservice");

// 其他中间件配置(路由、认证等)...

app.Run();

配置后,应用会自动将/serviceapi/myservice/api/file/...解析为/api/file/...,匹配控制器路由。

验证步骤

  1. 查看Ingress Controller日志,确认转发到后端的请求路径是否正确:
    kubectl logs <ingress-controller-pod-name> -n <ingress-namespace>
    
  2. 进入后端Web API Pod,直接测试路由是否正常:
    kubectl exec -it <webapi-pod-name> -n myservice -- curl http://localhost/api/file/{appId}/{key}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 13:50:12