2012-11-10 74 views
8

我想知道.NET是否有任何類用於簡化URL生成,類似於Path.Combine但是用於URL。.NET中的URL字符串生成

的功能的示例我在尋找:

string url = ClassName.Combine("http://www.google.com", "index") 
      .AddQueryParam("search", "hello world").AddQueryParam("pagenum", 3); 
// Result: http://www.google.com/index?search=hello%20world&pagenum=3 
+0

可能重複的[C#地址生成器類(http://stackoverflow.com/questions/1759881/c-sharp-url-builder-class) – jheddings

回答

7

我相信你正在尋找UriBuilder類。

爲統一資源標識符(URI)提供自定義構造函數,並修改Uri類的URI。

1

這裏有一個類似的問題,哪個環節兩個第三方庫:

C# Url Builder Class

據我所知,目前還沒有什麼「出的即裝即用」的。 NET,它允許流暢的接口構建UrlQueryString

0
// In webform code behind: 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Collections.Specialized; 

namespace testURL 
{ 
    public partial class _Default : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 

     protected void Button1_Click(object sender, EventArgs e) 
     { 
      NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty); 

      queryString["firstKey"] = "a"; 
      queryString["SecondKey"] = "b"; 

      string url=GenerateURL(queryString); // call function to get the url 
     } 

     private string GenerateURL(NameValueCollection nvc) 
     { 
      return "index.aspx?" + string.Join("&", Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key])))); 
     } 

    } 
} 


    // To get information to generate URL in MVC please check the following tutorial: 
    http://net.tutsplus.com/tutorials/generating-traditional-urls-with-asp-net-mvc3/