一、創建demo項目
1.新建webapi項目,命名為“DemoProject”
1 using Microsoft.AspNetCore.Mvc; 2 using System.Collections.Generic; 3 4 namespace DemoProject.Controllers 5 { 6 [Route("api/[controller]/[action]")] 7 [ApiController] 8 public class DefaultController : ControllerBase 9 { 10 static List<Student> list = new List<Student>() { 11 new Student(){ ID = "001", StudentName = "學生1", StudentAge = 16 }, 12 new Student(){ ID = "002", StudentName = "學生2", StudentAge = 18 }, 13 new Student(){ ID = "003", StudentName = "學生3", StudentAge = 17 } 14 }; 15 16 [HttpGet] 17 public List<Student> GetList() 18 { 19 return list; 20 } 21 22 [HttpGet] 23 public Student GetModel(string id) 24 { 25 return list.Find(t => t.ID == id); 26 } 27 } 28 29 public class Student 30 { 31 public string ID { get; set; } 32 public string StudentName { get; set; } 33 public int StudentAge { get; set; } 34 } 35 }
2.通過VS啟動,並且保證能正常訪問
二、創建Ocelot項目
1.新建webapi項目,命名為“OcelotProject”,不需要Controller
2.打開程序包管理器控制台,執行命令:Install-Package Ocelot
3.在項目根目錄下,新建配置文件“ocelot.json”,填寫為你自己的“DemoProject”的端口號
{ "ReRoutes": [ { "DownstreamPathTemplate": "/api/Default/GetList", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5963 } ], "UpstreamPathTemplate": "/GetList", "UpstreamHttpMethod": [ "Get" ] }, { "DownstreamPathTemplate": "/api/Default/GetModel?id={s1}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5963 } ], "UpstreamPathTemplate": "/GetModel?id={s1}", "UpstreamHttpMethod": [ "Get" ] } ] }
4.在Program.cs的CreateHostBuilder中加入
.ConfigureAppConfiguration(conf => { conf.AddJsonFile("ocelot.json", false, true); })
5.找到Startup.cs
在ConfigureServices中加入:
services.AddOcelot(Configuration);
在Configure中加入:
app.UseOcelot().Wait();
三、請求
通過VS啟動“OcelotProject”,由於配置中對外的路由為“/GetList”,所以訪問地址為:http://ip:port/GetList
GetModel的訪問地址為:http://ip:port/GetModel?id=002
代碼:https://files.cnblogs.com/files/shousiji/OcelotDemo.rar