目标框架 net 6.0 ocelot 18.0.0
程序.cs:
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
var builder = WebApplication.CreateBuilder(args);
var ocelotConfig = builder.Configuration.AddJsonFile(Path.Combine(builder.Environment.ContentRootPath, "ocelot.json"), optional: false, reloadOnChange: true);
builder.Services.AddOcelot(builder.Configuration);
builder.Services.AddControllers();
var app = builder.Build();
app.UseOcelot();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
ocelot.json:
{
"GlobalConfiguration": {
"BaseAddress": "https://localhost:7249"
},
"Routes": [
{
"DownstreamPathTemplate": "/api/WeatherForecast",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7249
}
],
"UpstreamPathTemplate": "/gtw/WeatherForecast",
"UpstreamHttpMethod": [ "Get" ]
}
]
}
WeatherForcastController.cs:
using Microsoft.AspNetCore.Mvc;
namespace DemoApiGateway.Controllers;
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
当我尝试调用 https://localhost:7249/gtw/WeatherForecast 或直接调用 https://localhost:7249/api/WeatherForecast 时,我得到响应 Http 404。
附:
在早期版本的 .net core (2.2) 中它可以工作。但它已被弃用,我想重建为 .net 的 LTS 版本。