.NETを使用してUriのホスト部分を置き換える最も良い方法は何ですか?
つまり:
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はあまり役に立たないようです。
System.UriBuilder はあなたが求めているものです...
string ReplaceHost(string original, string newHostName) {
var builder = new UriBuilder(original);
builder.Host = newHostName;
return builder.Uri.ToString();
}
@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;