Подтвердить что ты не робот

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

Каков наилучший способ замены хост-части 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:[email protected]/index.html", "newhostname");
Assert.AreEqual("http://user:[email protected]/index.html", s);
//...
string s = ReplaceHost("ftp://user:[email protected]", "newhostname");
Assert.AreEqual("ftp://user:[email protected]", s);
//etc.

System.Uri, похоже, мало помогает.

4b9b3361

Ответ 1

System.UriBuilder - это то, что вы после...

string ReplaceHost(string original, string newHostName) {
    var builder = new UriBuilder(original);
    builder.Host = newHostName;
    return builder.Uri.ToString();
}

Ответ 2

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