C# 替换 Uri 中的主机
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/479799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:01:58 来源:igfitidea点击:
Replace host in Uri
提问by Rasmus Faber
What is the nicest way of replacing the host-part of an Uri using .NET?
使用 .NET 替换 Uri 的主机部分的最佳方法是什么?
I.e.:
IE:
string ReplaceHost(string original, string newHostName);
//...
string s = ReplaceHost("http://oldhostname/index.html", "newhostname");
Assert.AreEqual("http://newhostname/index.html", s);
//...
string s = ReplaceHost("http://user:pass@oldhostname/index.html", "newhostname");
Assert.AreEqual("http://user:pass@newhostname/index.html", s);
//...
string s = ReplaceHost("ftp://user:pass@oldhostname", "newhostname");
Assert.AreEqual("ftp://user:pass@newhostname", s);
//etc.
System.Uri does not seem to help much.
System.Uri 似乎没有多大帮助。
采纳答案by Ishmael
System.UriBuilderis what you are after...
System.UriBuilder就是你所追求的......
string ReplaceHost(string original, string newHostName) {
var builder = new UriBuilder(original);
builder.Host = newHostName;
return builder.Uri.ToString();
}
回答by Drew Noakes
As @Ishmael says, you can use System.UriBuilder. Here's an example:
正如@Ishmael 所说,您可以使用 System.UriBuilder。下面是一个例子:
// the URI for which you want to change the host name
var oldUri = Request.Url;
// create a new UriBuilder, which copies all fragments of the source URI
var newUriBuilder = new UriBuilder(oldUri);
// set the new host (you can set other properties too)
newUriBuilder.Host = "newhost.com";
// get a Uri instance from the UriBuilder
var newUri = newUriBuilder.Uri;