Заменить хост в Ури - PullRequest
       14

Заменить хост в Ури

76 голосов
/ 26 января 2009

Каков наилучший способ замены хост-части Uri с помощью .NET?

т.е:.

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, кажется, не очень помогает.

Ответы [ 2 ]

126 голосов
/ 26 января 2009

System.UriBuilder - это то, что вам нужно ...

string ReplaceHost(string original, string newHostName) {
    var builder = new UriBuilder(original);
    builder.Host = newHostName;
    return builder.Uri.ToString();
}
42 голосов
/ 18 августа 2012

Как говорит @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;
...