如何使用C#替换请求URL中的参数?

问题描述 投票:0回答:1

我有n个请求网址,如下所示

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

我有下面的测试数据类,它有n个值。

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";
.......
.......
.......
}

我需要制作网址

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

在我的代码中,我将随机获取一个请求url(来自json文件),我需要用类中给出的值替换参数。可以这样做吗?如果是,请帮助。谢谢

我尝试过使用string.format() - 但它不起作用,因为我随机获取了url,我不确定需要替换哪个值。我也尝试使用插值,但发现没有帮助,除非我可以做类似的事情

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;

更新:经过一些谷歌搜索后,我发现我的问题与this非常相似。我可以使用第一个答案的备用选项2作为临时解决方案。

c# rest string-interpolation string.format
1个回答
1
投票

除非我明显忽略了这一点(并假设当你做新用户时所有的值都在;);)

你只是想要

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

然后像{user.id}这样的所有变量都被替换为值。例如“https://88722/456/testing1”,如果你需要{}那里你可以添加额外的{{与...

 string requesturl = $"https://{{{user.id}}}/{{{user.name}}}/testing1";
© www.soinside.com 2019 - 2024. All rights reserved.