【问题标题】:Replace host in Uri替换 Uri 中的主机
【发布时间】:2009-01-26 13:32:21
【问题描述】:

使用 .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 似乎没有多大帮助。

【问题讨论】:

    标签: c# .net uri


    【解决方案1】:

    System.UriBuilder 是你所追求的……

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

    【讨论】:

    • 我会推荐 Uri 类,但我错了。很好的答案。
    • 效果很好,请注意,如果您读取 Query 属性,它会以 ? 开头,如果您使用以 ? 开头的字符串设置 Query 属性,另一个 ?将被前置。
    • 你必须处理端口,如果它们是在原始或新指定的。
    【解决方案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;
    

    【讨论】:

    • 我怀疑通过调用newUriBuilder.Uri 来获取Uri 实例可能比格式化和解析它更好。
    • @Sam 你是对的,Uri 属性是一个更好的选择。谢谢。已更新。
    • 小心.Uri 电话。如果你在 UriBuilder 中有一些东西不能转换为有效的 Uri,它会抛出。例如,如果您需要一个通配符主机*,您可以将.Host 设置为此,但如果您调用.Uri,它会抛出。如果您调用 UriBuilder.ToString(),它将返回带有通配符的 Uri。
    猜你喜欢
    • 2018-03-21
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 2015-01-02
    相关资源
    最近更新 更多