質問

.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;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top