删除 StartUp.cs 文件,在 Program.cs 文件中添加如下内容
``` csharp
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
namespace ApiGateway
{
public class Program
{
public static void Main(string[] args)
{
new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
config
.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
.AddJsonFile("ocelot.json")
.AddEnvironmentVariables();
})
.ConfigureServices(services =>
{
services.AddOcelot().AddConsul();
})
.ConfigureLogging((hostingContext, logging) =>
{
//add your logging
})
.UseIISIntegration()
.Configure(app =>
{
app.UseOcelot().Wait();
})
.Build()
.Run();
}
}
}
```
注意:打开 Gateway.csproj 文件,更改
<PropertyGroup> <TargetFramework>netcoreapp2.2</TargetFramework> <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> </PropertyGroup>为
<PropertyGroup> <TargetFramework>netcoreapp2.2</TargetFramework> <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel> </PropertyGroup>至此,一个基础网关基本构建完成。
构建 Consul 服务
使用 Chocoletey 安装 Consul,
choco install consul新建一个文件夹以保存 Consul 服务配置
在 consul.d 文件夹中添加配置文件,内容如下:
{ "services": [{ "ID": "ServiceA", "Name": "ServiceA", "Tags": [ "ServiceAWebApi", "Api" ], "Address": "127.0.0.1", "Port": 8010, "Check": { "HTTP": "http://127.0.0.1:8010/Api/health", "Interval": "10s" } }, { "id": "ServiceB", "name": "ServiceB", "tags": [ "ServiceBWebApi","Api" ], "Address": "127.0.0.1", "Port": 8011, "Check": [{ "HTTP": "http://127.0.0.1:8011/Api/health", "Interval": "10s" } ] } ] }
启动 consul 服务
consul agent -dev -config-dir=./consul.d启动后在浏览器中输入 :8500/ui/ 以查看Consul服务
#### Postman 验证
F5 启动 Gateway 项目,启动 Postman 发送请求到 ServiceA 获取 Token。
使用 Token 请求 ServiceA Values 接口
当尝试使用 ServiceA 获取到的 Token 去获取 ServiceB 的数据时,请求也如意料之中返回 401
至此,一个由 .NET Core、IdentityServer4、Ocelot、Consul实现的基础架构搭建完毕。源码地址