Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add string value at the end of Base Address using HttpClientFactory?

I’m using HttpClientFactory to make http requests.

Here’s my code : –


namespace handleDeviceOperations
{
    
class Program
{

string operationID = String.Empty;
static async Task Main(string[] args)
{
    var serviceCollection = new ServiceCollection();
    ConfigureServices(serviceCollection);
    var services = serviceCollection.BuildServiceProvider();
    var httpClientFactory = services.GetRequiredService<IHttpClientFactory>();

    //Getting operationID from few other lines of code

    var httpClientGetOperations = httpClientFactory.CreateClient("getOperations");
    var request1 = await httpClientGetOperations.GetAsync("");
    var responseMessage1 = await request1.Content.ReadAsStringAsync();
}
private static void ConfigureServices(ServiceCollection services)
{

    services.AddHttpClient("getOperations", options =>
    {
        options.BaseAddress = new Uri("https://myurl.com/events/");

        options.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic","Auth_Value");
    });   
}
}

As you can see this is my Base Address : "https://myurl.com/events/"
Now, just before making the request here : –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var httpClientGetOperations = httpClientFactory.CreateClient("getOperations");
var request1 = await httpClientGetOperations.GetAsync("");

I want to add the operationID to the end of the Base Address such that the Base Address becomes something like this : –

"https://myurl.com/events/45872254"
//The string at the end will differ each time

This is a very necessary step as the request is completely dependent on the operationID parameter.

>Solution :

options.BaseAddress = new Uri("https://myurl.com/");
...
var id = 45872254;
var request1 = await httpClientGetOperations.GetAsync($"events/{id}");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading