Search code examples
c#nginxkubernetesasp.net-web-apinginx-ingress

Use Kubernetes Ingress with dynamic parameters to web API


I am having a problem using Kubernetes Ingress with a ASP.NET core web API.

Lets say I have a web API with three controllers (simplified code to demonstrate three routes /, /ep1, /ep2):

endpoints.MapGet("/", async context =>
{
    await context.Response.WriteAsync("##");
});

endpoints.MapGet("/ep1", async context =>
{
    await context.Response.WriteAsync("1");
});

endpoints.MapGet("/ep2", async context =>
{
    await context.Response.WriteAsync("2");
});

What I want is to define an ingress rule that will pass the internal route to the application:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: "true"
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  rules:
  - host: myhost.com
    http:
      paths:
      - path: /(/|$)(.*)
        pathType: Prefix
        backend:
          service:
            name: myservice
            port:
              number: 80

Then what I expect to happen is that browsing to myhost.com/ will return "##", myhost.com/ep1 will return "1" and myhost.com/ep2 will return "2" However, all three routes return "##"

Am I doing something wrong while configuring the ingress? Is it something that even possible when using ingress rules? If not, how do you create a controller that is using dynamic parameters? Let's say I want a web API that returns the amount in bank for some user ID, when specifying its ID in the GET path: myhost.com/balance/1312323, how can I implement this using a web API and ingress rules with Kubernetes?

Thanks for helping


Solution

  • Routing within the app should be handled by the app. So, there should be no need to define dynamic paths. Try this.

    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
      name: ingress
      annotations:
        nginx.ingress.kubernetes.io/rewrite-target: /
    spec:
      rules:
      - host: myhost.com
        http:
          paths:
          - path: /
            backend:
              service:
                name: myservice
                port:
                  number: 80