1

I want to create named HttpClients for each serve definition existing in the JSON file. But I have a problem with it. I do not know how to access this JSON file

JSON is defined like this in the project:

enter image description here

This file just contains a list of server names with their URLs:

{
  "servers": [
    {
      "name": "first",
      "url": "firstUrl"
    },
    {
      "name": "second",
      "url": "secondUrl"
    }
  ]
}

Then in the main file I want to use it and created named HttpClients for each of the existing URL :

builder.Services.AddHttpClient("Name", client =>
{
    client.BaseAddress = new Uri("Url");
    client.Timeout = new TimeSpan(0, 0, 30);
});

so later I could create a specific HttpClients depending on the params received:

public async Task<Players> GetPlayers(string serverName)
{
    var client = httpClientFactory.CreateClient(serverName);
    var list = await client.GetAsAsync<Players>("players.xml");
    return list;
}

2 Answers 2

2

You can read the JSON file and deserialize it to the model. Then you can add HttpClient services to the service collection using this model.

Create your models according to your JSON structure;

public class TestModel
{
    public List<Server> Servers { get; set; }
}

public class Server
{
    public string Name { get; set; }
    public string Url { get; set; }    
}

Add services;

var jsonContent = File.ReadAllText("yourfilepath", Encoding.UTF8);

var json = JsonConvert.DeserializeObject<TestModel>(jsonContent);

foreach (var server in json.Servers)
{
    builder.Services.AddHttpClient(server.Name, client =>
    {
        client.BaseAddress = new Uri(server.Url);
        client.Timeout = new TimeSpan(0, 0, 30);
    });
}

That should work.

If you want read JSON easily from your entire application, you can use my open-source library.

Sign up to request clarification or add additional context in comments.

Comments

2

You can add any json file to the builder's Configuration, and read its data.

public class ServerModel
{
    public string Name { get; set; }
    public string Url { get; set; }
}
builder.Configuration.AddJsonFile("ServerList/servers.json");
IEnumerable<ServerModel> servers = builder.Configuration.GetSection("servers").Get<IEnumerable<ServerModel>>();

foreach(var server in servers)
{
    builder.Services.AddHttpClient(server.Name, client =>
    {
        client.BaseAddress = new Uri(server.Url);
        client.Timeout = new TimeSpan(0, 0, 30);
    });
}

1 Comment

Typical situation: the accepted answer is what the OP asks, but your solution is what the OP should actually do. It's never clear what is the best action here. Probably combine both in one answer. Anyhow, +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.