Create a Demo project

1. Create a WebAPI project, name it DemoProject, and deselect HTTPS

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace DemoProject.Controllers{[Route("api/[controller]/[action]")]
    [ApiController]
    public class DefaultController : ControllerBase
    {
        static List<Student> list = new List<Student>() {
             new Student(){ ID = "001", StudentName = "Student 1", StudentAge = 16 },
             new Student(){ ID = "002", StudentName = Student 2 "", StudentAge = 18 },
             new Student(){ ID = "003", StudentName = "Students 3", StudentAge = 17}}; [HttpGet]
        public List<Student> GetList()
        {
            return list;
        }

        [HttpGet]
        public Student GetModel(string id)
        {
            returnlist.Find(t => t.ID == id); }}public class Student
    {
        public string ID { get; set; }
        public string StudentName { get; set; }
        public int StudentAge { get; set; }}}Copy the code

2. Start through VS and ensure normal access



2. Create Project Ocelot

1. Create a WebAPI project and name it “OcelotProject”. Deselect HTTPS and Controller is not required

2. Open the Package manager console and run the install-package Ocelot command



3. In the root directory of the project, create the configuration file Ocelot. Json and enter the port number of your 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"]]}}Copy the code

4. Add to CreateHostBuilder in program. cs

.ConfigureAppConfiguration(conf => {
    conf.AddJsonFile("ocelot.json".false.true);
})
Copy the code



5. Find Startup. Cs

Add to ConfigureServices:

services.AddOcelot(Configuration);
Copy the code

Add to Configure:

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

Third, the request

Start OcelotProject using VS. The external route in the configuration is /GetList, so the access address is http://ip:port/GetList



The access address for GetModel is: http://ip:port/GetModel? id=002

Code: files.cnblogs.com/files/shous…