API 网关 Ocelot .Net Core 6.1 设置

Dro*_*rap 5 asp.net-core ocelot .net-6.0

.Net 6 已删除启动类,我无法找到如何在新的 .Net 6 结构中配置 Ocelot。我找到了两种方法

 using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddOcelot()// 1.ocelot.json goes where?
// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddOcelot(); // 2.what is the use of this
Run Code Online (Sandbox Code Playgroud)

请告诉我

Xin*_*hen 7

添加ocelot.json在您的项目中调用的 json 文件。

然后像这样配置Program.cs

IConfiguration configuration = new ConfigurationBuilder()
                            .AddJsonFile("ocelot.json")
                            .Build();

var builder = WebApplication.CreateBuilder(args);
//.....
builder.Services.AddOcelot(configuration);

var app = builder.Build();

//........
app.UseOcelot();

//......
Run Code Online (Sandbox Code Playgroud)


小智 7

您可能已经解决了这个问题,因此这适用于所有正在寻找解决方案的其他开发人员。以下是添加 Ocelot 配置的两种方法。

\n
    \n
  1. JSON file在您的项目中添加一个名为ocelot.json项目,并在其中添加 ocelot 的配置。
  2. \n
  3. 该文件ocelot.json必须注册在Program.cs, Ocelot 才能加载 API 网关的配置。
  4. \n
\n

以下是如何注册 Ocelot 配置的两个示例。

\n

1.添加Ocelot配置,无需环境检查

\n
\nusing Ocelot.DependencyInjection;\nusing Ocelot.Middleware;\n\nvar builder = WebApplication.CreateBuilder(args);\n\nIConfiguration configuration = new ConfigurationBuilder()\n                            .AddJsonFile("ocelot.json")\n                            .Build();\n\nbuilder.Services.AddOcelot(configuration);\n\nvar app = builder.Build();\n\nawait app.UseOcelot();\n\napp.MapGet("/", () => "Hello World!");\n\napp.Run();\n\n
Run Code Online (Sandbox Code Playgroud)\n

正如您所看到的,我们使用从 ocelot.json 加载配置.ConfigurationBuilder()。然后,我们将配置解析为将 Ocelot 添加到服务容器的方法,然后再注册其中间件。

\n

2.添加当前环境的Ocelot配置

\n

我倾向于有多个环境用于生产、测试​​、本地开发等...我们可以通过检查我们正在运行的环境来完成此操作,而不是使用 Ocelot 的特定配置文件重写/更新配置加载器。

\n
\nusing Ocelot.DependencyInjection;\nusing Ocelot.Middleware;\n\nvar builder = WebApplication.CreateBuilder(args);\n\nIConfiguration configuration = new ConfigurationBuilder()\n                            .AddJsonFile($"ocelot.{builder.Environment.EnvironmentName}.json", true, true)\n                            .Build();\n\nbuilder.Services.AddOcelot(configuration);\n\nvar app = builder.Build();\n\nawait app.UseOcelot();\n\napp.MapGet("/", () => "Hello World!");\n\napp.Run();\n\n
Run Code Online (Sandbox Code Playgroud)\n

在上面的代码中我们用来IHostEnvironment获取当前的环境名称。然后我们可以使用字符串插值将环境名称动态插入到 ocelot 配置文件的字符串中。

\n

为此,您必须为每个环境添加一个新的配置文件,如下所示:

\n
ocelot.json\n\xe2\x94\x9c\xe2\x94\x80 ocelot.Development.json\n\xe2\x94\x9c\xe2\x94\x80 ocelot.Local.json\n\xe2\x94\x9c\xe2\x94\x80 ocelot.Test.json\n
Run Code Online (Sandbox Code Playgroud)\n