在Uri

问题描述 投票:0回答:3

使用.NET替换URI的主机零件的最佳方法是什么?

I.E。:

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
3个回答
181
投票
System.uribuilder

是您所追求的... string ReplaceHost(string original, string newHostName) { var builder = new UriBuilder(original); builder.Host = newHostName; return builder.Uri.ToString(); }



45
投票

// 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;



0
投票
这是我用来处理这种常见情况的精致代码:

public static Uri ReplaceHost(Uri original, string newHostName) { var builder = new UriBuilder(original); var newhost = new Uri(newHostName.Contains("://") ? newHostName : "http://" + newHostName); builder.Host = newhost.Host; builder.Port = newhost.Port == 80 ? builder.Port : newhost.Port; return builder.Uri; }

注意,如果您不指定新端口,则保留旧端口
	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.