使用.NET替换URI的主机零件的最佳方法是什么?
I.E。:
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似乎没有太大帮助。
// 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;
public static Uri ReplaceHost(Uri original, string newHostName)
{
var builder = new UriBuilder(original);
var newhost = new Uri(newHostName.Contains("://") ? newHostName : "http://" + newHostName);
builder.Host = newhost.Host;
builder.Port = newhost.Port == 80 ? builder.Port : newhost.Port;
return builder.Uri;
}
注意,如果您不指定新端口,则保留旧端口