替换Uri中的主机

Ras*_*ber 77 .net c# uri

使用.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.
Run Code Online (Sandbox Code Playgroud)

System.Uri似乎没什么帮助.

Ish*_*ael 131

System.UriBuilder就是你追求的......

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


Dre*_*kes 42

正如@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;
Run Code Online (Sandbox Code Playgroud)

  • 我怀疑通过调用`newUriBuilder.Uri`获取`Uri`实例可能更好,而不是格式化和解析它. (3认同)