An overview of the

Ocelot is oriented to use. NET people who run micro-service/service-oriented architectures that need a unified entry point in the system. In particular, I wanted easy integration with IdentityServer references and hosted tokens. Ocelot is a bunch of middleware in a particular order. Ocelot manipulates the HttpRequest object to the state specified by its configuration until it reaches the request Builder middleware, where it creates an HttpRequestMessage object that is used to make requests to downstream services. The middleware that makes the request is the last thing in Ocelot’s pipeline. It does not call the next middleware. There is a piece of middleware that maps HttpResponseMessage to an HttpResponse object and then returns it to the client. Basically, it has many other functions.

Code implementation

1. Create API client 1

2. Create API gateway test

Nuget installs Ocelot

4, add ConfigureAppConfiguration Program files

 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>();
                });
    }
Copy the code

5. Startup File configuration

  services.AddOcelot(Configuration);

   app.UseOcelot().Wait();
Copy the code

6. Add ocelot. Json file to gateway project

{
  "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" ]
    }
  ]
}
Copy the code

7. Two projects were run and tested

The code address

Gitee.com/conanOpenSo…