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

Time:06-03

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 : -

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.

CodePudding user response:

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