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



我有 n 个请求 url,如下所示

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;

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

除非我明显错过了重点(让我们假设当你做新用户((;

你只是想要

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

最新更新