skip to Main Content

Here I am trying to implement Ocelot for API Gateway for my multiple micro services. I have Seven Micro services which have lots of API almost 550 APIs. While preparing ocelot.json it is a huge file which seems unmaintainable. For which I want to have different json array objects for each services. Those array objects to be inserted to in routes array of ocelot.json. I have a sample ocelot.json like this:

{
   "Routes": [
    {
      "DownstreamPathTemplate": "/api/ObjectHeads/GetObjectHeadFromBudget?{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 59035
        }
      ],
      "UpstreamPathTemplate": "/ObjectHeads/GetObjectHeadFromBudget?{everything}",
      "UpstreamHttpMethod": [ "Get" ]
    },
    {
      "DownstreamPathTemplate": "/api/ObjectHeads/GetObjectHeadByDepartmentWise?{everything}",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 44358
        }
      ],
      "UpstreamPathTemplate": "/ObjectHeads/GetObjectHeadByDepartmentWise?{everything}",
      "UpstreamHttpMethod": [ "Get" ]
    }
   ],
   "GlobalConfiguration": {
   "BaseUrl": "https://localhost:7000"
   }
}

It is working absolutely fine I am able to perform get, post from different micro services. Now my concern is there a way to add json array objects in routes array in the ocelot.json? I am bit new to the json as I never worked on it. Is there a way out for managing such stuff. I am sure that somebody may have gone through such situation, there may be a solution. My program.cs looks simple like this.

var builder = WebApplication.CreateBuilder(args);

builder.Configuration
    .AddJsonFile("ocelot.json")
    .AddJsonFile($"ocelot.{builder.Environment.EnvironmentName}.json");

 builder.Services.AddOcelot()
    .AddDelegatingHandler<RequestLogger>()
    .AddCacheManager(settings => settings.WithDictionaryHandle())
    .AddCustomLoadBalancer((serviceProvider, downstreamRoute, serviceDiscoveryProvider) =>
    {
        return new CustomLoadBalancer(serviceDiscoveryProvider.Get);
    });

var app = builder.Build();

app.UseOcelot();

app.Run();

Any solutions and suggestions are highly appreciated please.

2

Answers


  1. you can download json directly , not using config

        var path = @"C:...";
        // or maybe you can try this
        var path = Directory.GetCurrentDirectory();
    
        var filePath = Path.Combine(path, "ocelot.json");
        var json = File.ReadAllText(filePath);
    
        var jObj = JObject.Parse(json);
    
        var newRoute = new
        {
            DownstreamPathTemplate = "/api/ObjectHeads/GetObjectHeadByDepartmentWise?{everything}",
            DownstreamScheme = "https",
            DownstreamHostAndPorts = new[] {
            new {
             Host= "localhost",
              Port= 44358
            }
          },
            UpstreamPathTemplate = "/ObjectHeads/GetObjectHeadByDepartmentWise?{everything}",
            UpstreamHttpMethod = new string[] { "Get" }
        };
        
         ((JArray)jObj["Routes"]).Add(JObject.FromObject(newRoute));
         
          File.WriteAllText(filePath,jObj.ToString());
    
    Login or Signup to reply.
  2. For json text starts with {} is type of JObject. For starts with [] is type of JArray. And you need Nuget Package Newtonsoft.Json to convert string to JObject or JArrary

    Below is a sample of read the first "route" and added it to the json file.

    var directoryPath = Directory.GetCurrentDirectory();
    string filePath = directoryPath + "\ocelot.json"; //get file path
    
    StreamReader sr = new StreamReader(filePath);       
    string jsonString = sr.ReadToEnd();       //read the file to a string
    sr.Close();
    
    var jsonData = (JObject)JsonConvert.DeserializeObject(jsonString); // the string starts with '{}' so we convert to JObject
    Console.WriteLine(jsonData);   //to check the jobject we get
    var routes = (JArray)jsonData["Routes"];  //You can get element inside JObject by jsonData["a"]["b"] ,but the value of "Routes" starts with "[]" so convert it to JArray
    var route1 = routes[0];       //You can get Arrary elements by index
    
    StreamWriter sw = new StreamWriter(filePath);
    routes.Add(route1);          //add one more 1st route as example 
    jsonData["Routes"] = routes;    //jsonData can be update by this syntax
    sw.Write(jsonData);
    sw.Close();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search