C#Asp.net开发.NET

.Netcore 2.0 Ocelot Api网关教程(1)-

2018-04-05  本文已影响373人  Weidaicheng

Ocelot(Github)
Ocelot官方文档(英文)
本文不会介绍Api网关是什么以及Ocelot能干什么
需要对Api网关及Ocelot有一定的理论了解

开始使用Ocelot搭建一个入门级Api网关

1.新建3个WebApi项目,分别命名为OcelotGetway、WebApiA、WebApiB


webapi项目.png

2.在OcelotGetway项目的Nuget包管理器中搜索Ocelot并安装

Nuget包管理器.png
或者在程序包管理器中输入
Install-Package Ocelot安装

3.在OcelotGetway项目中新建json文件并命名为configuration.json在VS中右键修改为“始终复制”


configuration.json.png

4.编辑configuration.json文件并添加以下内容

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/values",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/webapia/values",
      "UpstreamHttpMethod": [ "Get" ]
    },
    {
      "DownstreamPathTemplate": "/api/values",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5002
        }
      ],
      "UpstreamPathTemplate": "/webapib/values",
      "UpstreamHttpMethod": [ "Get" ]
    }
  ]
}

5.修改OcelotGetway项目的Startup类如下

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddOcelot(new ConfigurationBuilder()
            .AddJsonFile("configuration.json")
            .Build());
}

public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    
    await app.UseOcelot();

    app.UseMvc();
}

6.修改WebApiA和WebApiB项目的ValuesController分别为

[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1 from webapi A", "value2 from webapi A" };
}
[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1 from webapi B", "value2 from webapi B" };
}

7.编辑Properties目录下的launchSettings.json文件中的applicationUrl(每个文件中有两个,只改下边的就可以)


launchSettings.json.png

分别设置3个项目的applicationUrl为:

8.分别运行WebApiA、WebApiB、OcelotGetway
浏览器分别访问
http://localhost:5000/webapia/values
http://localhost:5000/webapib/values

运行效果.png
源码下载

完,下一篇将介绍路由

上一篇 下一篇

猜你喜欢

热点阅读