代码之家  ›  专栏  ›  技术社区  ›  Rasmus Faber

替换Uri中的主机

  •  100
  • Rasmus Faber  · 技术社区  · 17 年前

    使用替换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.
    

    系统。乌里似乎没有多大帮助。

    2 回复  |  直到 17 年前
        1
  •  159
  •   Pang Ajmal PraveeN    5 年前

    System.UriBuilder 这就是你想要的。..

    string ReplaceHost(string original, string newHostName) {
        var builder = new UriBuilder(original);
        builder.Host = newHostName;
        return builder.Uri.ToString();
    }
    
        2
  •  44
  •   Drew Noakes    13 年前

    正如@Ishmael所说,你可以使用系统。小便器。这里有一个例子:

    // 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;
    
    推荐文章