Asp.Net Core + Ocelot 網關搭建:路由簡單配置


前言

  Ocelot是一個基於中間件的網關實現,功能有很多。從淺入深簡單學習並記錄一下吧。本篇就是一個簡單的路由配置實現。

DEMO 搭建

  首先建立三個項目。Api.User,Api.Article,Api.GateWay.ApiGateWay項目中引入Ocelot Nuget包.添加配置文件Ocelot.json.

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/{all}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 60001
        }
      ],
      "UpstreamPathTemplate": "/user/{all}",
      "UpstreamHttpMethod": ["GET","POST"]
    },
    {
      "DownstreamPathTemplate": "/{all}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 60002
        }
      ],
      "UpstreamPathTemplate": "/article/{all}",
      "UpstreamHttpMethod": ["GET","POST"]
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:60003/"
  }
}

  啟動的時候將配置文件加進去,並且Startup中添加相應的中間件:services.AddOcelot(),app.UseOcelot();

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
             .ConfigureAppConfiguration((hostingContext, config) =>
             {
                 config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                       .AddJsonFile("ocelot.json", optional: true, reloadOnChange: true)
                       .AddEnvironmentVariables();
             }).UseStartup<Startup>();

  啟動三個項目,運行效果如下:

總結

  這樣就能實現將網關做為統一入口,統一管理了。后續在加上各種Ocelot的功能實現。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM