2011-04-16 58 views
0

我需要將返回從URL部分正確的URL(如在瀏覽器)創建HTTP URL字符串

string GetUrl(string actual,string path) { 
    return newurl; 
} 

例如函數:

GetUrl('http://example.com/a/b/c/a.php','z/x/c/i.php') -> http://example.com/a/b/c/z/x/c/i.php 

GetUrl('http://example.com/a/b/c/a.php','/z/x/c/i.php') -> http://example.com/z/x/c/i.php 

GetUrl('http://example.com/a/b/c/a.php','i.php') -> http://example.com/a/b/c/i.php 

GetUrl('http://example.com/a/b/c/a.php','/o/d.php?b=1') -> http//example.com/o/d.php?b=1 

GetUrl('http://example.com/a/a.php','./o/d.php?b=1') -> http//example.com/a/o/d.php?b=1 

阿努建議?

+2

可能的重複[Path.Combine for Urls?](http://stackoverflow.com/questions/372865/path-combine-for-urls) – 2011-04-16 12:09:29

+0

@Daniel A. White:謝謝,新的Uri(Uri baseUri,字符串relativeUri)按預期工作 – ekapek 2011-04-16 12:26:18

回答

3

你需要的是System.UriBuilder類:http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx

還有在CodeProject一個輕量級的解決方案上的System.Web犯規depent:http://www.codeproject.com/KB/aspnet/UrlBuilder.aspx

還有一個查詢字符串構建(但我還沒有嘗試過):http://weblogs.asp.net/bradvincent/archive/2008/10/27/helper-class-querystring-builder-chainable.aspx

+0

但是沒有System.Web的任何輕型解決方案? – ekapek 2011-04-16 12:09:41

+0

順便說一下,System.Web.UrlBuilder取決於System.Web&顯示一個GUI。另一方面,System.UriBuilder沒有輔助依賴關係,但沒有其他解決方案的功能。 – 2011-04-16 12:12:50

0

什麼:

string GetUrl(string actual, string path) 
{ 
    return actual.Substring(0, actual.Length - 4).ToString() + "/" + path; 
} 
1
public string ConvertLink(string input) 
    { 
     //Add http:// to link url 
     Regex urlRx = new Regex(@"(?<url>(http(s?):[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)", RegexOptions.IgnoreCase); 

     MatchCollection matches = urlRx.Matches(input); 

     foreach (Match match in matches) 
     { 
      string url = match.Groups["url"].Value; 
      Uri uri = new UriBuilder(url).Uri; 
      input = input.Replace(url, uri.AbsoluteUri); 
     } 
     return input; 
    } 

代碼找到與正則表達式的字符串中的每一個環節,然後用UriBuilder以協議添加到鏈接,如果不存在。由於「http://」是默認的,因此如果沒有協議存在,它將被添加。

+0

這正是我需要的,thx。 – 2015-05-22 11:27:27