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)
请告诉我
添加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 配置的两种方法。
\nJSON file在您的项目中添加一个名为ocelot.json项目,并在其中添加 ocelot 的配置。ocelot.json必须注册在Program.cs, Ocelot 才能加载 API 网关的配置。以下是如何注册 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\nRun Code Online (Sandbox Code Playgroud)\n正如您所看到的,我们使用从 ocelot.json 加载配置.ConfigurationBuilder()。然后,我们将配置解析为将 Ocelot 添加到服务容器的方法,然后再注册其中间件。
我倾向于有多个环境用于生产、测试、本地开发等...我们可以通过检查我们正在运行的环境来完成此操作,而不是使用 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\nRun Code Online (Sandbox Code Playgroud)\n在上面的代码中我们用来IHostEnvironment获取当前的环境名称。然后我们可以使用字符串插值将环境名称动态插入到 ocelot 配置文件的字符串中。
为此,您必须为每个环境添加一个新的配置文件,如下所示:
\nocelot.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\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
9919 次 |
| 最近记录: |