一日一技:ASP.NET Core Api网关Ocelot初探

概述

Ocelot面向使用.NET运行微型服务/面向服务的体系结构的人员,这些体系结构需要在系统中具有统一的入口点。特别是我想与IdentityServer参考和承载令牌轻松集成。Ocelot是按特定顺序排列的一堆中间件。Ocelot将HttpRequest对象操作到由其配置指定的状态,直到到达请求构建器中间件,在该中间件中它创建一个HttpRequestMessage对象,该对象用于向下游服务发出请求。发出请求的中间件是Ocelot管道中的最后一件事。它不会调用下一个中间件。有一块中间件可将HttpResponseMessage映射到HttpResponse对象,然后将其返回给客户端。基本上,它具有许多其他功能。

代码实现

1、新建api客户端1

 

 2、新建api 网关test

 

 3、nuget安装Ocelot

 

 

 

4、Program文件添加ConfigureAppConfiguration

 

 

 public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(conf =>
            {
                conf.AddJsonFile("ocelot.json", false, true);
            })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

 

5、Startup文件配置

  services.AddOcelot(Configuration);

 

   app.UseOcelot().Wait();

6、网关项目下添加文件ocelot.json

 

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/WeatherForecast/GetList",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5000
        }
      ],
      "UpstreamPathTemplate": "/GetList",
      "UpstreamHttpMethod": [ "Get" ]
    },

    {
      "DownstreamPathTemplate": "/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5000
        }
      ],
      "UpstreamPathTemplate": "/{everything}",
      "UpstreamHttpMethod": [ "Post" ]
    },
    {
      "DownstreamPathTemplate": "/api/WeatherForecast/GetModel?id={s1}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5000
        }
      ],
      "UpstreamPathTemplate": "/GetModel?id={s1}",
      "UpstreamHttpMethod": [ "Get" ]
    }
  ]
}

 

7、2个项目运行,测试

 

 

代码地址

https://gitee.com/conanOpenSource_admin/Example/commit/b3b5a6b15a060b46c5ecd2ea31f0d36791cda18c

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值