在我的c#应用程序中,我正在构建一个解析url的例程,用适当的数据替换url的任何部分。
例如,如果我有一个像这样的url:
api.domain.com/users/{id}
用户提供id,我将id替换为给定值。
这很简单:
if(path.Contains("{id}") path = path.Replace("{id}", id);
但是,我希望能够在没有提供id的情况下从url中删除{id},这样最终的url就是:api.domain.com/users
我还希望它能够智能地删除路径中间的项,这样如果url是:api.domain.com/users/{id}/photos
我会得到:api.domain.com/users/photos
为此,我不会提前知道密钥的文本,因此{id}可以是以下任何内容:
{name} {sometext} {anyvalue}
但我知道每一个都必须包含在大括号中。
任何帮助都将不胜感激!
发布于 2016-11-09 03:03:06
你可以这样做:
public string UrlReplace(string Url, string key, string value = "")
{
var replaceString = "{" + key + "}"; //get the string to replace
//if the value is empty remove the slash
if (string.IsNullOrEmpty(value))
{
//find the index of the replace string in the url
var index = url.IndexOf(replaceString) + replaceString.Length;
if (url[index] == '/')
{
url = url.Remove(index, 1); //if the character after the string is a slash, remove it
}
}
return url.Replace(replaceString, value); //replace the string with the value
}然后你就会像这样使用它
string url = "api.domain.com/users/{id}/photos";
url = UrlReplace(url,"id","test");
//returns "api.domain.com/users/test/photos"
url = UrlReplace(url, "id", "");
//returns "api.domain.com/users/photos"https://stackoverflow.com/questions/40494144
复制相似问题