2009-01-26 25 views
67

Cách tốt nhất để thay thế phần lưu trữ của Uri bằng .NET là gì?Thay thế máy chủ tại Uri

tức là .:

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:[email protected]/index.html", "newhostname"); 
Assert.AreEqual("http://user:[email protected]/index.html", s); 
//... 
string s = ReplaceHost("ftp://user:[email protected]", "newhostname"); 
Assert.AreEqual("ftp://user:[email protected]", s); 
//etc. 

System.Uri dường như không giúp được gì nhiều.

Trả lời

103

System.UriBuilder là những gì bạn đang theo đuổi ...

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

Cảm ơn đó chính xác là những gì tôi đang tìm kiếm. –

+0

Tôi đã đề nghị lớp Uri, nhưng tôi đã sai. Câu trả lời tốt. –

+0

Hoạt động tuyệt vời, chỉ cần lưu ý rằng nếu bạn đọc thuộc tính Truy vấn, nó được thêm vào trước bằng dấu? Và nếu bạn đặt Thuộc tính truy vấn bằng chuỗi bắt đầu bằng ?, một thuộc tính khác? sẽ được thêm vào trước. – Dave

41

Như @Ishmael nói, bạn có thể sử dụng System.UriBuilder. Dưới đây là ví dụ:

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

Tôi nghi ngờ có thể tốt hơn để có được cá thể 'Uri' bằng cách gọi' newUriBuilder.Uri' thay vì định dạng và phân tích cú pháp nó. – Sam

+0

@Bạn nói đúng, thuộc tính ['Uri'] (http://msdn.microsoft.com/en-us/library/system.uribuilder.uri.aspx) là một lựa chọn tốt hơn nhiều. Cảm ơn. Đã cập nhật. –

Các vấn đề liên quan