Search code examples
c#reststring-interpolationstring.format

How can I replace the parameters in my request url using C#?


I have n number of request urls, like below

https://{user.id}/{user.name}/testing1
https://{user.number}/{user.name}/testing1
https://{user.age}/{user.height}/testing1
https://{user.gender}/{user.name}/testing1
https://{user.height}/{user.age}/testing1
https://{user.weight}/{user.number}/testing1

I have the below test data class which has n number of values.

public class User{
public string id = "123";
public string name = "456";
public string age = "789";
public string gender = "1478";
public string height = "5454";
public string weight = "54547";
public string number = "88722";
.......
.......
.......
}

And I need to make the url

https://{user.number}/{user.name}/testing1 into 
https://{88722}/{456}/testing1

In my code, I will be randomly getting a request url(from a json file) and i need to replace the parameters with the values given in the class. Can this be done? If yes please help. Thanks

I have tried using string.format() - but it doesnot work, because I am randomly getting the url and I am not sure which value needs to be replaced. I also tried using the interpolation, but found not helpful either unless i can do something like

User user = new User();
string requesturl = GetRequestJSON(filepath);

//The requesurl variable will have a value like 
//"https://{user.id}/{user.name}/testing1";

string afterreplacing = $+requesturl;

Update: After some more googling, I found out that my question is very much similar to this. I can use the first answer's alternate option 2 as a temporary solution.


Solution

  • Unless I am clearly missing the point (and lets assume all the values are in when you do new user(); )

    You just want

    User user = new User();
    string requesturl = $"https://{user.id}/{user.name}/testing1";
    

    then all the variables like {user.id} are replaced with values. such as "https://88722/456/testing1" if you need the {} in there you can add extra {{ to go with such as

     string requesturl = $"https://{{{user.id}}}/{{{user.name}}}/testing1";