Joel
Joel

Reputation: 8938

Excluding Swagger from YARP routing

I've got a use case where I want to host both an API and its frontend on the same port. I use YARP to do this.

So all requests to https://localhost:5001 will by default be routed to https://localhost:5173/. However, the minimal API routes (/api) have precedence and will not be routed by YARP. This works well.

I'm trying to add Swagger into the mix and I have an issue where the requests for its static content will be routed through YARP. For example: https://localhost:5001/api/swagger/index.html will load correctly, but https://localhost:5001/api/swagger/swagger-ui.css will be routed by YARP.

This is my setup:

var builder = WebApplication.CreateBuilder(args);

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

builder.Services
    .AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));

var app = builder.Build();

app.MapGet("/api/hello", () => "Hello World!");

app.UseSwagger();
app.UseSwaggerUI(options =>
{
    options.RoutePrefix = "api/swagger";
});

app.MapReverseProxy();

app.Run();

Config:

  "ReverseProxy": {
    "Routes": {
      "route1": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "{**catch-all}"
        }
      }
    },
    "Clusters": {
      "cluster1": {
        "HttpClient": {
          "SslProtocols": [
            "Tls12"
          ]
        },
        "Destinations": {
          "cluster1/destination1": {
            "Address": "https://localhost:5173/"
          }
        }
      }
    }
  }

What can I do to fix this? I haven't been able to figure out how to exclude all /api/swagger routes from YARP.

Upvotes: 4

Views: 1463

Answers (2)

GeorgeF0
GeorgeF0

Reputation: 431

I think it's a bug, see https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/2599. I use slightly different setup but I had the same problem. As per the GitHub issue I rearranged my code to look like this:

// do these before UseRouting
app.MapOpenApi();
app.UseSwaggerUI();

// this needs to come after UseSwaggerUI
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapMyApplicationMinimalApi();

// finally the YARP stuff
app.MapForwarder("/{**catch-all}", proxyTo);

app.Run();

Upvotes: 0

navark
navark

Reputation: 169

Add those calls before mapping your proxy:

app.UseStaticFiles();

app.UseRouting();

Upvotes: 0

Related Questions