我一直在为自己寻找相同的解决方案,但在 GitHub 上只发现了一条评论,它对我帮助很大
因此,您需要创建自定义中间件来重写 Ocelot 的 DownstreamRoute:
public static async Task InvokeAsync(HttpContext httpContext, Func<Task> next)
{
var downstreamRoute = httpContext.Items.DownstreamRoute();
var yourServiceName = //get query string parameter from httpContext;
//rewrite any parameter that you want
httpContext.Items.UpsertDownstreamRoute(
new DownstreamRoute(
downstreamRoute.Key,
downstreamRoute.UpstreamPathTemplate,
downstreamRoute.UpstreamHeadersFindAndReplace,
downstreamRoute.DownstreamHeadersFindAndReplace,
downstreamRoute.DownstreamAddresses,
tenantServiceName,
...
));
}
然后在 Startup.cs 中调用它:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// some other code
var configuration = new OcelotPipelineConfiguration
{
PreQueryStringBuilderMiddleware = async (ctx, next) =>
{
await RouteContextRetrieverMiddleware.InvokeAsync(ctx, next);
await next.Invoke();
}
};
app.UseOcelot(configuration).GetAwaiter().GetResult();
}