Search code examples
c#urlhttprequesturi

Concatenate URL with variable in C#


I am trying to concatenate a URL with a variable and then the "rest" of the URL.

It goes like this:

variableName = "1234";

....

var requestMessage = new HttpRequestMessage(HttpMethod.Get, _configuration["MY_BASE_URL" + variableName + "/theRestOfTheUrl"]);

Where the "MY_BASE_URL" is saved as an variable as: "http://mytestsite.com/users/"

but when doing this I get the error:

"error":"An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.

What am I doing wrong? When just passing:

var requestMessage = new HttpRequestMessage(HttpMethod.Get, _configuration["MY_BASE_URL"]);

where I instead have named "MY_BASE_URL" as "http://mytestsite.com/users/1234/theRestOfTheUrl" I get no errors, but I would to be able to add the variableName too + what comes after, with the option of having the variableName being dynamic - and therefore I can't give it as an entire hardcoded string.


Solution

  • _configuration["MY_BASE_URL"] is a configuration variable which returns your base URL i.e http://mytestsite.com/users/, now you need to append variable value to it then hard coded string /theRestOfTheUrl.

    Instead of writing everything inside _configuration key, write it with string interpolation

    Try

    string url = $"{_configuration["MY_BASE_URL"]}{variableName}/theRestOfTheUrl";
    Console.WriteLine(url); // http://mytestsite.com/users/1234/theRestOfTheUrl
    

    Your code will look like

    variableName = "1234";
    
    ....
    
    string url = $"{_configuration["MY_BASE_URL"]}{variableName}/theRestOfTheUrl";
    var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
    

    POC: .net Fiddle