# Ocelot與路由共存 ### 引言 在Asp.Net Core中使用了Ocelot做網關之後,其自身的Api路由就不起作用了,尋了許久的解決方法,終於找到一個,主要是使用MapWhen判斷Ocelot的配置是否符合,是則走轉發路由,否則走自身路由,步驟如下: ### 1.先創建以下類 ``` ...
Ocelot與路由共存
引言
在Asp.Net Core中使用了Ocelot做網關之後,其自身的Api路由就不起作用了,尋了許久的解決方法,終於找到一個,主要是使用MapWhen判斷Ocelot的配置是否符合,是則走轉發路由,否則走自身路由,步驟如下:
1.先創建以下類
using Ocelot.Configuration.Repository;
using Ocelot.DownstreamRouteFinder.Finder;
using Ocelot.Middleware;
namespace GateWay.Extensions
{
public static class OcelotExtensions
{
public static IApplicationBuilder UseOcelotWhenRouteMatch(this IApplicationBuilder app)
=> UseOcelotWhenRouteMatch(app, new OcelotPipelineConfiguration());
public static IApplicationBuilder UseOcelotWhenRouteMatch(this IApplicationBuilder app,
Action<OcelotPipelineConfiguration> pipelineConfigurationAction)
{
var pipelineConfiguration = new OcelotPipelineConfiguration();
pipelineConfigurationAction?.Invoke(pipelineConfiguration);
return UseOcelotWhenRouteMatch(app, pipelineConfiguration);
}
public static IApplicationBuilder UseOcelotWhenRouteMatch(this IApplicationBuilder app, OcelotPipelineConfiguration configuration)
{
app.MapWhen(context =>
{
// 獲取 OcelotConfiguration
var internalConfigurationResponse =
context.RequestServices.GetRequiredService<IInternalConfigurationRepository>().Get();
if (internalConfigurationResponse.IsError || internalConfigurationResponse.Data.Routes.Count == 0)
{
// 如果沒有配置路由信息,不符合分支路由的條件,直接退出
return false;
}
var internalConfiguration = internalConfigurationResponse.Data;
var downstreamRouteFinder = context.RequestServices
.GetRequiredService<IDownstreamRouteProviderFactory>()
.Get(internalConfiguration);
// 根據請求以及上面獲取的Ocelot配置獲取下游路由
var response = downstreamRouteFinder.Get(context.Request.Path, context.Request.QueryString.ToString(),
context.Request.Method, internalConfiguration, context.Request.Host.ToString());
// 如果有匹配路由則滿足該分支路由的條件,交給 Ocelot 處理
return !response.IsError
&& !string.IsNullOrEmpty(response.Data?.Route?.DownstreamRoute?.FirstOrDefault()
?.DownstreamScheme);
}, appBuilder => appBuilder.UseOcelot(configuration).Wait());
return app;
}
}
}
2.在Program.cs調用
app.UseOcelotWhenRouteMatch(); // 此處調用
app.UseRouting();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();