解决方案: 版本较高的Ocelot中,配置路由使用的应该是Routes,而不是ReRoutes。具体配置可以继续阅读下文
在学习使用Ocelot的时候,跟着学习的步骤一步步走过来,(没有看官方文档),在调用的时候一直出现404。(ocelot使用的版本是16.0 环境是 .netCore3.1)
具体代码如下:
//program配置
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(c =>
{
c.AddJsonFile("configuration.json", optional: false, reloadOnChange: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
});
}
//startUp配置
public class Startup
{
public Startup(IConfiguration configuration)
{
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot();
/// services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//使用新的请求处理管道
app.UseOcelot();
//删除旧的请求处理管道
//if (env.IsDevelopment())
//{
// app.UseDeveloperExceptionPage();
//}
//app.UseHttpsRedirection();
//app.UseRouting();
//app.UseAuthorization();
//app.UseEndpoints(endpoints =>
//{
// endpoints.MapControllers();
//});
}
}
//configuration.json 文件内容
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/{url}", //服务地址--url为变量
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5859
}
],
"UpstreamPathTemplate": "/T5859/{url}", //网关地址--url为变量
"UpstreamHttpMethod": [ "Get", "Post" ] //,
//"GlobalConfiguration": {
// "BaseUrl": "http://localhost:1600"
//}
}
]
}
调用具体地址出现如下图结果:

后面被迫去查看官网的文档,看了半天也没看出问题。最后逐字查看,查到了原因。 版本较高的Ocelot中,配置路由使用的应该是Routes,而不是ReRoutes
具体修改代码如下:
//configuration.json 文件内容
{
"Routes": [
{
"DownstreamPathTemplate": "/api/{url}", //服务地址--url为变量
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5859
}
],
"UpstreamPathTemplate": "/T5859/{url}", //网关地址--url为变量
"UpstreamHttpMethod": [ "Get", "Post" ] //,
//"GlobalConfiguration": {
// "BaseUrl": "http://localhost:1600"
//}
}
]
}
修改了此名称之后,就可以正常使用了。所以调用第三方的插件,还是要看文档啊!!!